コード例 #1
0
def getImage():
    global camera
    global time_between_picture
    global nightMode

    imageFile = None
    if camera == None:
        camera = camara.initCamera()
        camara.resolucionHD()
        utils.myLog('Waiting {}s  for camera warn'.format(TIME2INITCAMERA))
        time.sleep(TIME2INITCAMERA)
    if camera != None:
        if nightMode:
            utils.myLog('nigth Mode')
            camara.addDateNight()
            imageFile = camara.getImageNight()
        else:
            if datetime.datetime.now().hour >= 20 or datetime.datetime.now(
            ).hour < 7:
                camara.addDateNight()
            else:
                camara.addDate()
            imageFile = camara.getImage()
    if time_between_picture == 0 or time_between_picture > 10000:
        camera = camara.closeCamera()
    return imageFile
コード例 #2
0
def initCamera():
    global camera
    utils.myLog('Initting camera')
    camera = PiCamera()  # creamos el objeto camara
    if camera != None:
        utils.myLog('Camera Ready!')
    return camera
コード例 #3
0
def sendMsg2Admin(message):
    utils.myLog(message)
    if config.ADMIN_USER != None:
        TelegramBase.send_message(utils.getStrDateTime() + " " + message,
                                  config.ADMIN_USER)
    else:
        utils.myLog('No admin user id')
コード例 #4
0
ファイル: raspi.py プロジェクト: javacasm/RaspiZeroLapse
def checkPythonProcessRunning(pythonScript):
    counter = 0
    for proc in psutil.process_iter():
        if pythonScript in proc.cmdline():
            counter += 1
            utils.myDebug('cmd: ' + str(proc.cmdline()))
    utils.myLog(pythonScript + ' está en ejecución {} veces'.format(counter))
    return counter
コード例 #5
0
def getExplicitData():
    strData = getFullData()
    utils.myLog('STRData:' + strData)
    data = strData.split(config.separadorDatosArduino)
    strData = ''
    for d in data:
        strData += d + '\n'
    return strData
コード例 #6
0
def checkMQTTSubscription(client, userdata, message):
    topic = str(message.topic)
    message = str(message.payload.decode("utf-8"))
    #if topic.startswith(topic_sub):
    #    pass ## TODO: check topics
    MQTTData[topic] = [utils.getStrDateTime(), message]

    utils.myLog('MQTT: ' + utils.getStrDateTime() + ' ' + topic + ' - ' +
                message)
コード例 #7
0
ファイル: raspi.py プロジェクト: javacasm/RaspiZeroLapse
def getThrottled():
    strThrotled, strError = executeProcess(cmdGetTrottled[0],
                                           cmdGetTrottled[1])
    strThrotled = str(strThrotled)
    strError = str(strError)
    utils.myLog(strThrotled)
    if strError != None:
        utils.myLog(strError)
    return str(strThrotled)
コード例 #8
0
def init():
    global camera
    arduinoSerialPort, puertoDetectado = arduinoUtils.detectarPuertoArduino()
    if (puertoDetectado != ''):
        utils.myLog("\n ** ARDUINO CONECTADO EN " + puertoDetectado + " ** ")
        if arduinoSerialPort != None:
            riego.init(arduinoSerialPort)
        else:
            utils.myLog("None Arduino Port")
    camera = camara.initCamera()
コード例 #9
0
def initMQTT():
    global ourClient
    ourClient = mqtt.Client(
        "CBT_bot_mqtt")  # Create a MQTT client object with this id
    ourClient.connect(config.MQTT_SERVER,
                      1883)  # Connect to the test MQTT broker
    utils.myLog('Conectado a MQTT broker ' + config.MQTT_SERVER)
    ourClient.subscribe(config.BaseTopic_sub + '/#')  # Subscribe to the topic
    ourClient.on_message = checkMQTTSubscription  # Attach the messageFunction to subscription
    ourClient.loop_start()  # Start the MQTT client
    utils.myLog('MQTT client started')
コード例 #10
0
def getData():
    global bus
    global calibration_params

    if calibration_params == None:
        init()
# leemos los datos
    data = bme280.sample(bus, address, calibration_params)

    # los mostramos en otro formato
    utils.myLog(str(data))
    return data.temperature, data.pressure, data.humidity, data.timestamp, data.id
コード例 #11
0
def publish(client, topic, message):
    try:
        utils.myLog('MQTT > ' + str(topic) + ':' +
                    str(message.decode('utf-8')))
        mqttResult = client.publish(topic, message)
        # utils.myLog(str(mqttResult))
        #if mqttResult.is_published():
        #       utils.myLog('Publicado')
        #else:
        #   utils.myLog('No publicado')
    except KeyboardInterrupt:
        pass
    except Exception as e:
        utils.myLog('Publish>' + str(e))
コード例 #12
0
def initMQTT():
    ourClient = mqtt.Client(
        'CBT_bot_mqtt' +
        config.TELEGRAM_API_TOKEN)  # Create a MQTT client object with this id
    ourClient.on_message = checkMQTTSubscription  # Attach the messageFunction to subscription
    ourClient.on_log = on_log
    ourClient.on_connect = on_connect
    ourClient.connect(config.MQTT_SERVER,
                      1883)  # Connect to the test MQTT broker
    utils.myLog('Conectado a MQTT broker ' + config.MQTT_SERVER)
    topic2Subscribe = config.BaseTopic_sub + '/#'
    print(topic2Subscribe)
    ourClient.subscribe(topic2Subscribe)  # Subscribe to the topic
    ourClient.loop_start()  # Start the MQTT client
    utils.myLog('MQTT client started')
    return ourClient
コード例 #13
0
def getDataArduino(arduinoSerialPort,PAUSA):
    '''
    Funcion para acceso a ARDUINO y obtencion de datos en tiempo real   ---
    version mejorada para evitar errores de comunicacion
    ante eventuales fallos de la conexion.
    '''
   #  global arduinoSerialPort
    FLAG_buscandoConexion = False

    try:
        arduinoSerialPort.flushInput() #eliminar posibles restos de lecturas anteriores
        arduinoSerialPort.flushOutput()#abortar comunicaciones salientes que puedan estar a medias

    except Exception as e :
        utils.myLog ("Error getDataArduino: " + str(e))
 
    try:
        #enviar comando para que ARDUINO reaccione. El prefijo b (byte) es opcional en python 2.x pero obligatorio en 3.x
        sendCommand(arduinoSerialPort,config.getDataCommand, config.TimeoutRespuesta) 

        utils.myLog("Sent " + str(config.getDataCommand) + ' command')
        #pausa para que arduino tenga tiempo de reaccionar y dejar la informacion en el puerto Serie
        time.sleep( PAUSA)

        #revisar si hay datos en el puerto serie
        datos = readAllData(arduinoSerialPort)
        utils.myLog(datos)
        return datos
    except Exception as e:
        utils.myLog('Error: ' + str(e))
        #si llegamos aqui es que se ha perdido la conexion con Arduino  :(
        print ("\n_______________________________________________")
        if FLAG_buscandoConexion == False:      #primera vez que llegamos aqui
            print ("\n == CONEXION PERDIDA == ")
            FLAG_buscandoConexion = True        #para no repetir el texto mientras se reestablece la conexion

        tiempoInicio = time.time()
        ActualTime = time.time()
        print ("    Reconectando...")
        while (ActualTime - tiempoInicio < 10): #Control del tiempo entre consultas de ARDUINO  :)
            arduinoSerialPort.close() #cerrar puerto anterior por seguridad
            arduinoSerialPort,puertoDetectado = detectarPuertoArduino() #detactamos automaticamente el puerto
            ActualTime = time.time()
            if (puertoDetectado != ''):
               # arduinoSerialPort = serial.Serial(puertoDetectado, VELOCIDAD_PUERTO_SERIE) #usamos el puerto detectado
                print ("\n")
                FLAG_buscandoConexion = False
                print (" ** COMUNICACION REESTABLECIDA en "  + puertoDetectado + " ** \n")
                print (utils.epochDate(time.time()))
                print ("_______________________________________________\n\n")
                break
    print ("Arduino sin datos disponibles")
    return None   # notificamos un problema de lectura de datos para que se intente tomar otra muestra lo antes posible

#-----------------------------------------------------------------------------------------
#-----------------------------------------------------------------------------------------  
     
コード例 #14
0
def main():
    """Run the bot."""
    global update_id
    global chat_id
    global time_between_picture
    global camera
    global nightMode
    global bReboot

    init()

    bot = telegram.Bot(config.TELEGRAM_API_TOKEN)

    # get the first pending update_id, this is so we can skip over it in case
    # we get an "Unauthorized" exception.
    try:
        update_id = bot.get_updates()[0].update_id
    except IndexError:
        update_id = None

    logging.basicConfig(
        format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')

    last_Beat = int(round(time.time() * 1000))
    last_picture = 0

    while True:
        try:
            now = int(round(time.time() * 1000))
            if time_between_picture > 0 and (
                    now - last_picture) > time_between_picture:
                imageFile = getImage()
                message = 'TimeLapse: ' + imageFile
                utils.myLog(message)
                last_picture = now
                TelegramBase.send_message(message, chat_id)
            if (now - last_Beat) > 60000:  # 60 segundos
                utils.myLog(botName + ' test')
                last_Beat = now
            if bReboot:
                bReboot = False
                sendMsg2Admin('Reboot in 10 seconds!!!')
                # time.sleep(10)
                # raspi.reboot()

            updateBot(bot)
        except NetworkError:
            time.sleep(0.1)
        except Unauthorized:
            # The user has removed or blocked the bot.
            update_id += 1
        except KeyboardInterrupt:
            utils.myLog('Interrupted')
            sys.exit(0)
        except Exception as e:
            message = 'Excepcion!!: ' + str(e)
            sendMsg2Admin(message)
コード例 #15
0
def main():
    """Run the bot."""
    global update_id
    global chat_id

    init()

    bot = telegram.Bot(config.TELEGRAM_API_TOKEN)

    # get the first pending update_id, this is so we can skip over it in case
    # we get an "Unauthorized" exception.
    try:
        update_id = bot.get_updates()[0].update_id
    except IndexError:
        update_id = None

    utils.myLog('Init TelegramBot')

    logging.basicConfig(
        format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')

    last_Beat = int(round(time.time() * 1000))
    while True:
        try:
            now = int(round(time.time() * 1000))
            if (now - last_Beat) > 60000:  # 60 segundos
                utils.myLog('BotTest')
                last_Beat = now
            updateBot(bot)
        except NetworkError:
            time.sleep(0.1)
        except Unauthorized:
            # The user has removed or blocked the bot.
            update_id += 1
        except KeyboardInterrupt:
            utils.myLog('Interrupted')
            sys.exit(0)
        except Exception as e:
            utils.myLog('Excepcion!!: ' + str(e))
コード例 #16
0
def checkMQTTSubscription(client, userdata, message):
    global bUpdateCalderaStatus, bEsperandoRespuestaCaldera, bInitConsola
    topic = str(message.topic)
    message = str(message.payload.decode('utf-8'))
    MQTTData[topic] = [utils.getStrDateTime(), message]
    logmsg = 'MQTT < ' + topic + ' - ' + message
    utils.myLog(logmsg)
    if topic == config.topicCalderaStatus:
        bUpdateCalderaStatus = True
    elif topic == config.topic_subCalderaAction:
        bEsperandoRespuestaCaldera = True
    elif topic == config.topic_subInitConsola:
        bInitConsola = True
        utils.myLog('got initconsole')
    elif topic in dumbTopics:
        pass
    else:
        utils.myLog('Unknown msg: ' + logmsg)
コード例 #17
0
def do_sql_cmd(sql=""):
    conn = sqlite3.connect("courses_db.db")
    c = conn.cursor()
    sql = sql.strip()
    if re.search(r"^insert|^update|^delete", sql, re.I):
        try:
            res = c.execute(sql)
            conn.commit()
            return {"rowcount": c.rowcount, "data": "ok"}
        except Exception as e:
            myLog(f"""def do_sql_cmd: error exec sql:\n{e}\n{sql}""", 1)
            return {"rowcount": -1, "data": e}
    elif re.search(r"^select|^width", sql, re.I):
        try:
            res = c.execute(sql).fetchall()
            return {"rowcount": len(res), "data": res}
        except Exception as e:
            myLog(f"""def do_sql_cmd: error exec sql:\n{e}\n{sql}""")
            return {"rowcount": -1, "data": f"""{e}\n{sql} """}
    else:
        myLog(f"""not valid sql\n{sql}""")
        return {"rowcount": -1, "data": "unknown query"}
コード例 #18
0
"""

Usamos psutil

"""

v = '0.4'

import raspi
import utils

cuantos = raspi.checkPythonProcessRunning('raspiCarbot.py')

utils.myLog('Hay {} instancias'.format(cuantos))
コード例 #19
0
def apagaRele(releID):
    global arduinoSerialPort
    if arduinoSerialPort != None:
        arduinoUtils.sendCommand(arduinoSerialPort,config.setReleCommand + str(releID).encode('utf-8') + config.releOffCommand, config.TimeoutRespuesta)
    else:
        utils.myLog('arduinoSerialPort == None')      
コード例 #20
0
def riegoOffSector(sectorID):
    if sectorID not in config.Sectores:
        utils.myLog("Sector {} no definido".format(sectorID))
    apagaRele(sectorID)
    bombaOff()
コード例 #21
0
def riegoOnSector(sectorID):
    if sectorID not in config.Sectores:
        utils.myLog("Sector {} no definido".format(sectorID))
    enciendeRele(sectorID)
    bombaOn()
コード例 #22
0
ファイル: raspi.py プロジェクト: javacasm/RaspiZeroLapse
def getIP():
    hostname = socket.gethostname()
    ip_address = socket.gethostbyname(hostname + '.local')
    utils.myLog(f"IP Address: {ip_address}")
    return ip_address
コード例 #23
0
ファイル: raspi.py プロジェクト: javacasm/RaspiZeroLapse
def getHostName():
    hostname = socket.gethostname()
    utils.myLog(f"Hostname: {hostname}")
    return hostname
コード例 #24
0
ファイル: camara.py プロジェクト: javacasm/RaspiZeroLapse
def initCamera():
    global camera
    camera = PiCamera() # creamos el objeto camara
    utils.myLog('Init camara')
    return camera
コード例 #25
0
ファイル: raspi.py プロジェクト: javacasm/RaspiZeroLapse
def getTemp():
    # /opt/vc/bin/vcgencmd get_throttled
    strTemp = executeCommand(cmdGetTemp[0] + ' ' + cmdGetTemp[1])
    utils.myLog(strTemp)
    return strTemp
コード例 #26
0
ファイル: raspi.py プロジェクト: javacasm/RaspiZeroLapse
def halt():
    utils.myLog("Shutdown! bye!")
    os.system("sudo shutdown -h now")
コード例 #27
0
def updateBot(bot):
    """Answer the message the user sent."""
    global update_id
    global chat_id
    global time_between_picture
    global welcomeMsg
    global nightMode
    global bReboot

    #utils.myLog('Updating telegramBot')
    # Request updates after the last update_id
    for update in bot.get_updates(offset=update_id, timeout=10):
        update_id = update.update_id + 1

        if update.message:  # your bot can receive updates without messages
            # Proccess the incoming message
            comando = update.message.text  # message text
            command_time = update.message.date  # command date
            user = update.message.from_user  #User full objetct
            chat_id = int(update.message.from_user.id)
            user_real_name = user.first_name  #USER_REAL_NAME
            if chat_id not in config.ALLOWED_USERS:
                message = 'User: {} not allowed. Chat_id {} command: {}. Will be reported'.format(
                    str(user_real_name), str(chat_id), comando)
                sendMsg2Admin(message)
                break
            TelegramBase.chat_ids[user_real_name] = [command_time, chat_id]
            utils.myLog('Command: ' + comando + ' from user ' +
                        str(user_real_name) + ' in chat id:' + str(chat_id) +
                        ' at ' + str(command_time))
            if comando == cmdStart:
                update.message.reply_text(welcomeMsg,
                                          reply_markup=user_keyboard_markup)
            elif comando == cmdHi:
                update.message.reply_text('Hello {}'.format(
                    update.message.from_user.first_name),
                                          reply_markup=user_keyboard_markup)
            elif comando == cmdInfo:
                answer = 'Info: ' + utils.getStrDateTime(
                ) + '\n==========================\n\n' + 'Tiempo entre imágenes: ' + getTimeLapseStr(
                ) + '\n ' + str(len(os.listdir(
                    config.ImagesDirectory))) + ' imágenes'
                update.message.reply_text(
                    answer,
                    parse_mode=telegram.ParseMode.MARKDOWN,
                    reply_markup=user_keyboard_markup)
            elif comando == cmdHelp:
                bot.send_message(chat_id=chat_id,
                                 text=commandList,
                                 reply_markup=user_keyboard_markup)
            elif comando == cmdUsers:
                sUsers = TelegramBase.getUsersInfo()
                TelegramBase.send_message(sUsers, chat_id)
            elif comando == cmdDayMode:
                nightMode == False
                update.message.reply_text('Day mode',
                                          reply_markup=user_keyboard_markup)
            elif comando == cmdNightMode:
                nightMode == True
                update.message.reply_text('Night mode',
                                          reply_markup=user_keyboard_markup)
            elif comando == cmdPhoto:
                answer = getImage()
                utils.myLog(answer)
                TelegramBase.send_picture(answer, chat_id)
                update.message.reply_text(
                    answer,
                    parse_mode=telegram.ParseMode.MARKDOWN,
                    reply_markup=user_keyboard_markup)
            elif comando == cmdLastPhoto:
                imagenes = os.listdir(config.ImagesDirectory)
                answer = config.ImagesDirectory + sorted(imagenes)[-1]
                TelegramBase.send_picture(answer, chat_id)
                update.message.reply_text(
                    answer,
                    parse_mode=telegram.ParseMode.MARKDOWN,
                    reply_markup=user_keyboard_markup)
            elif comando == cmdListPhotos:
                imagenes = sorted(os.listdir(config.ImagesDirectory))
                answer = str(
                    len(imagenes)) + ' Imágenes\n----------------------\n'
                utils.myDebug(answer)
                contadorImagenes = 1
                for imagen in imagenes:
                    answer += str(contadorImagenes) + ' ' + imagen + '\n'
                    contadorImagenes += 1
                utils.myDebug(answer)
                if len(imagenes) > 70:
                    answer = answer[0:2041] + ' \n...'
                update.message.reply_text(
                    answer,
                    parse_mode=telegram.ParseMode.MARKDOWN,
                    reply_markup=user_keyboard_markup)
            elif comando.startswith('/N'):
                numero = int(comando[2:])
                imagenes = sorted(os.listdir(config.ImagesDirectory))
                answer = config.ImagesDirectory + imagenes[numero]
                utils.myLog(answer)
                TelegramBase.send_picture(answer, chat_id)
                update.message.reply_text(
                    answer,
                    parse_mode=telegram.ParseMode.MARKDOWN,
                    reply_markup=user_keyboard_markup)
            elif comando.startswith('/T'):
                time_between_picture = int(comando[2:])
                answer = getTimeLapseStr()
                utils.myLog(answer)
                update.message.reply_text(
                    answer,
                    parse_mode=telegram.ParseMode.MARKDOWN,
                    reply_markup=user_keyboard_markup)
            elif comando.startswith('/image'):
                answer = config.ImagesDirectory + comando[1:]
                TelegramBase.send_picture(answer, chat_id)
                update.message.reply_text(
                    answer,
                    parse_mode=telegram.ParseMode.MARKDOWN,
                    reply_markup=user_keyboard_markup)
            elif comando == cmdTemp:
                answer = raspi.getTemp()
                utils.myLog(answer)
                update.message.reply_text(
                    answer,
                    parse_mode=telegram.ParseMode.MARKDOWN,
                    reply_markup=user_keyboard_markup)
            elif comando == cmdDF:
                answer = raspi.getDiskUsed()
                utils.myLog(answer)
                update.message.reply_text(
                    answer,
                    parse_mode=telegram.ParseMode.MARKDOWN,
                    reply_markup=user_keyboard_markup)
            elif comando == cmdIP:
                answer = raspi.getIP()
                utils.myLog(answer)
                update.message.reply_text(
                    answer,
                    parse_mode=telegram.ParseMode.MARKDOWN,
                    reply_markup=user_keyboard_markup)
            elif comando == cmdReboot:
                answer = 'Reboot in 10 seconds!!!'
                utils.myLog(answer)
                update.message.reply_text(
                    answer,
                    parse_mode=telegram.ParseMode.MARKDOWN,
                    reply_markup=user_keyboard_markup)
                bReboot = True
            else:
                update.message.reply_text('echobot: ' + update.message.text,
                                          reply_markup=user_keyboard_markup)
コード例 #28
0
ファイル: raspi.py プロジェクト: javacasm/RaspiZeroLapse
def reboot():
    utils.myLog("Shutdown! bye!")
    os.system("sudo reboot -f now")
コード例 #29
0
ファイル: raspi.py プロジェクト: javacasm/RaspiZeroLapse
def getPublicIP():
    fqn = os.uname()[1]
    ext_ip = urllib.request.urlopen('https://www.whatismyip.org/').read()
    utils.myLog("Host: %s " % fqn, " IP extena: %s " % ext_ip)
    return ext_ip
コード例 #30
0
ファイル: raspi.py プロジェクト: javacasm/RaspiZeroLapse
def init():
    utils.myLog('RaspiUtils ' + v)