Ejemplo n.º 1
0
def lambda_handler(event, context):

    sqs = boto3.resource('sqs')
    queue = sqs.get_queue_by_name(QueueName='CC-HW2')

    for message in queue.receive_messages():

        body = json.loads(message.body)
        location = body['Location']
        foodtype = body['FoodType']
        date = body['Date']
        time = body['Time']
        people = body['People']
        phone = body['Phone']
        message.delete()

        dynamodb = boto3.resource('dynamodb')
        table = dynamodb.Table('yelp-resturants')

        # elastic search
        es_url = 'https://search-restaurants-l7a6popsqvxfdqctb4sebw2scu.us-east-1.es.amazonaws.com/elasticdomain/_search?q=' + foodtype
        response = requests.get(es_url)
        data = response.json()
        data_list = []
        for i in range(0, 3):
            data_list.append(
                data['hits']['hits'][i]['_source']['RestaurantID'])

        # dynamodb
        response = []
        for i in range(3):
            response.append(table.get_item(Key={'BusinessID': data_list[i]}))

        restaurant_name_list = []
        restaurant_location_list = []

        for item1 in response:
            print(item1["Item"]["address"])
            restaurant_location_list.append(item1["Item"]['address'])
            restaurant_name_list.append(item1["Item"]['Name'])

        result = []

        for j in range(3):
            stringVariable = str(j + 1) + ". " + restaurant_name_list[
                j] + "located at " + restaurant_location_list[j] + "."
            result.append(stringVariable)

        stringToOutput = ""
        for k in range(3):
            stringToOutput = stringToOutput + result[k] + " , "
        message = "Hello! Here are my " + foodtype + " restaurant suggestions for " + people + " people, for " + date + " at " + time + " : \n"
        message = message + stringToOutput

        # SNS code
        client = boto3.client('sns')
        # client.subscribe(TopicArn = 'arn:aws:sns:us-east-1:028352437066:CC-HW2', Protocol='Email', Endpoint = mail)
        # client.publish(TopicArn = 'arn:aws:sns:us-east-1:028352437066:CC-HW2', Message = message)
        client.publish(PhoneNumber=phone, Message=message)
    return 0
Ejemplo n.º 2
0
def hue_connect(ip):
    global hueBridge
    hueBridge = phue.Bridge(ip)
    try:
        # Note: If Hue data is saved, then this will always succeed, even if the Hue isn't actually on the network!
        hueBridge.connect()  # Press on the Hue button before this line runs
    except:
        print(
            "Error connecting to Hue", ip,
            "Check if it's connected to the network and make sure the button is pressed."
        )
        errorData = {
            "status": "hydra_failed",
            "error": 91,
            "errorMessage": "Connecting to Hue failed",
            "request": {
                "route": "hueconnect"
            }
        }
        client.publish(hueBaseReturnTopic + "/connect", json.dumps(errorData))
    else:
        errorData = {
            "status": "ok",
            "request": {
                "route": "hueconnect"
            },
            "username": hueBridge.username
        }
        client.publish(hueBaseReturnTopic + "/connect", json.dumps(errorData))
Ejemplo n.º 3
0
def onUrlFound(url):
    """Called by onPacketFound, if the packet contains a url."""
    url = resolveUrl(url)
    client.publish(topic="iotg5/podc", payload=url, qos=0)
    sys.stdout.write("\n/*          Eddystone-URL         */\n")
    sys.stdout.write(url)
    sys.stdout.write("\n")
    sys.stdout.flush()
    if "e.io" in url:
        params = url.split('?')[1].split('&')
        import json
        with open('./sensors.json') as f:
            sensors = json.load(f)

        for param in params:
            split_param = param.split('=')
            index = int(split_param[0])
            dist = float(split_param[1])
            sensors[index] = dist
        #print(sensors)

        json = json.dumps(sensors)
        f = open("./sensors.json", "w")
        f.write(json)
        f.close()
Ejemplo n.º 4
0
def enviar10min():
    '''
    Envía ao canal de resultados o valor da transmitancia calculado a partir dos 
    valores de temperatura recollidos nos últimos 10 minnutos.
    Faise o envío despois de que se comprobe se o últimio minutal que se vai calcular
    corresponde cun dezminutal.
    '''
    global temps, minutal
    data = dt.datetime.utcnow().strftime('%Y%m%d_%H')
    datas = [
        data + '{:02}'.format(m)
        for m in list(range(minutal, minutal - 10, -9))
    ]
    transmitancia, erro = temps.calcularTransmitancia(datas,
                                                      fluxo='horizontal')
    #    condicion = (temps['data'] >= datas[1]) & (temps['data'] <= datas[0])
    #    transmitancia = calcularTransmitancia(temps[condicion])
    if (not transmitancia is None):
        client.publish(resultados['dezminutal'], transmitancia)
    else:
        pass
    if (not erro is None):
        client.publish(erros['dezminutal'], erro)
    else:
        pass
Ejemplo n.º 5
0
def enviar1min():
    '''
    Envía ao canal de resultados o valor da transmitancia calculado a partir
    dos valores de temperatura recollidos no úlitmo minuto.
    Mentres se está calculando e enviando o resultado, queda bloqueada a recepcción
    doutros mensaxes 'enviar1min', ao finalizar o envío actualízase o valor do
    minuto actual e desbloquéase a recepción de 'enviar1min'.
    O bloqueo da mensaxe 'enviar1min' faise capturando as mensaxes que aparezan
    e non facendo nada até que a variable global 'enviando' estea a True.
    '''
    global temps, minutal, enviando
    data = dt.datetime.utcnow().strftime("%Y%m%d_%H") + '{:02}'.format(minutal)
    transmitancia, erro = temps.calcularTransmitancia(data, fluxo='horizontal')
    #    condicion = (temps['data'] == data)
    #    transmitancia = calcularTransmitancia(temps[condicion])
    if (not transmitancia is None):
        client.publish(resultados['minutal'], transmitancia)
        enviarThing(transmitancia)
    else:
        pass
    if (not erro is None):
        client.publish(erros['minutal'], erro)
    else:
        pass
    minutal = (minutal + 1) % 60
    enviando = False
def on_connect(client, userdata, flags, rc):
    global minutal
    print("Conectado co rc: " + str(rc))
    # Cada vez que conecta co servidor mqtt
    client.subscribe(xeral + "#")  # Suscribimos a todas as canles
    client.publish(xestion['ordes'],
                   'pausar')  # Estado a Off. Agardamos sinal de On
    minutal = dt.datetime.utcnow().minute  # Actualizamos tempo de referencia
def enviarInst():
    global temps, minutal
    data = dt.datetime.utcnow().strftime("%Y%m%d_%H") + '{:02}'.format(minutal)
    transmitancia = temps.calcularTransmitancia(data, fluxo='horizontal')
    #    condicion = (temps['data'] == data)
    #    transmitancia = calcularTransmitancia(temps[condicion])
    if (not transmitancia is None):
        client.publish(resultados['instantaneo'], transmitancia)
    else:
        pass
Ejemplo n.º 8
0
def on_message(client, userdata, msg):
    global temps, minutal, recibirOk, enviando
    now = dt.datetime.utcnow()
    agora = now.strftime("%Y%m%d_%H%M")
    topic = str(msg.topic)
    mensaxe = msg.payload.decode('utf-8')
    if (topic in xestion.values() and mensaxe in ordes):
        logger.info('Mensaxe recibida')
        if ('pausar' in mensaxe):
            recibirOk = False
        elif ('recibir' in mensaxe):
            minutal = dt.datetime.utcnow(
            ).minute  # Actualizamos tempo de referencia
            recibirOk = True
            logger.info('Recibindo ok')
        elif ('enviar' in mensaxe):
            enviar(mensaxe)
    elif (topic in difMinimaTemp.values()):
        #        difMinima = re.findall(r'-{0,1}\d+.\d+', mensaxe)
        #        difMinima = float(difMinima)
        temps.setDiferenciaMinima(float(mensaxe))
    elif (recibirOk and topic in sensores.values()):
        valores_raw = re.findall(r'-{0,1}\d+.\d+', mensaxe)
        valores = [float(i) for i in valores_raw]
        temps.engadir(agora, topic, valores)
        ##        valores = [float(i) for i in mensaxe[:-2].split('; ')]
        #        # Se xa existen valores para un tempo determinado...
        #        if(temps.size > 0 and temps[(temps['data'] == agora) & (temps['sensor'] == topic)]):
        #            condicion = (temps['data'] == agora) & (temps['sensor'] == topic)
        #            # ...engádeos ao final
        #            temps[condicion]['valores'][0].extend(valores)
        #        else:
        #            # Se non crea unha nova entrada con eses valores para o sensor e tempo preciso
        #            temps = np.append(temps, np.array([(agora, topic, valores)], dtype=tipo))
        # Envíanse periodicamente resultados peticións de resultados minutais e
        # dezminutais. Solicítase o envío cun minuto de retraso para dar tempo
        # aos sensores enviaren as medidas e así acumular os resultados do minuto
        # anterior.
        # Como cada vez que se envía unha solicitude de minutal, actulízase o
        # tempo ao minuto seguinte, avalíase antes se o minuto é de fin de
        # dezminutal, para solicitar o mesmo.
        #print('enviando: ', enviando, ' minutal: ', minutal, ' now.minute-2: ', \
        #      (now.minute-2)%60, ' ok? ', not enviando and minutal == (now.minute-2)%60)
        mssg_log = 'enviando: ' + str(enviando) + ' minutal: ' + str(minutal) + \
                   ' now.minute-2: '+ str((now.minute-2)%60) + ' ok? ' + \
                    str(not enviando and minutal == (now.minute-2)%60)
        logger.info(mssg_log)
        if (not enviando and minutal == (now.minute - 2) %
                60):  #Envía minutal cun minuto de retraso
            enviando = True
            if (minutal % 10 == 0):  #Enviar 10minutal cun minuto de retraso
                client.publish(xestion['ordes'], 'enviar10min')
            client.publish(xestion['ordes'], 'enviar1min')
Ejemplo n.º 9
0
def insert_cerradura():
    password = request.json['password']
    posicion = request.json['posicion']
    hora_inicio = request.json['hora_inicio']
    hora_fin = request.json['hora_fin']

    nuevo_candado = "0;" + password + ";" + posicion
    user.on_message = on_message
    user.loop_start()
    #hl.agregar_candado(hora_inicio, hora_fin, posicion)
    # hl.agregar_candado(hora_inicio, hora_fin, posicion)
    client.publish(topico, nuevo_candado)
    return jsonify(nuevo_candado)
def enviarResume():
    '''
    Envía o valor actual da transmitancia tendo en conta todos os valores recollidos
    até o momento.
    '''
    global temps
    datas = None
    transmitancia = temps.calcularTransmitancia(datas, fluxo='horizontal')
    #    transmitancia = calcularTransmitancia(temps)
    if (not transmitancia is None):
        client.publish(resultados['resume'], transmitancia)
    else:
        pass
Ejemplo n.º 11
0
def publish_auth_fail_msg(client, error):
    # The format of this object is similar to the HomeWizard's own errors
    errorMsg = {
        70: 'Could not login to HomeWizard',
        71: 'Invalid payload',
        72: 'Already connected to HomeWizard'
    }

    data = {
        'status': 'failed_hydra',
        'error': error,
        'errorMessage': errorMsg[error],
        'request': {
            'route': 'hydralogin'
        }
    }
    string = json.dumps(data)
    client.publish(hydraAuthTopic + "/results", string, BASE_QOS)
Ejemplo n.º 12
0
def on_message(client, userdata, msg):
    global messageQueue
    global connectAuthThread

    if (msg.topic.startswith(homewizardBaseTopic)):
        print(get_time_string(), "Recieved message for HomeWizard at",
              msg.topic, str(msg.payload))
        # Process each message in a seperate thread to minimise waiting for IO (url requests)
        if homewizardBaseUrl is not None:
            threading.Thread(target=process_message,
                             args=(client, msg, 1)).start()
        else:
            publish_fail_msg(client, msg, 4)

    elif (msg.topic.startswith(hydraStatusTopic)):
        # get-status returns some data about our status
        if (msg.payload.decode("utf-8") == "get-status"):
            serial = ""
            if homewizardBaseUrl is not None:
                serial = get_serial(homewizardBaseUrl)
            client.publish(
                hydraStatusTopic + "/results",
                json.dumps({
                    'status': 'ok',
                    'request': {
                        'route': 'hydrastatus'
                    },
                    'serial': serial
                }))

    elif (msg.topic.startswith(hydraAuthTopic)):
        # Only accept an auth message if we aren't processing one yet
        if ((connectAuthThread is None)
                or (connectAuthThread.is_alive() == False)):
            connectAuthThread = threading.Thread(target=process_auth_request,
                                                 args=(client, msg))
            connectAuthThread.start()

    elif (msg.topic.startswith(hueBaseTopic)):
        threading.Thread(target=process_hue_message,
                         args=(client, msg)).start()
Ejemplo n.º 13
0
def publish_fail_msg(client, msg, error):
    # The format of this object is similar to the HomeWizard's own errors
    errorMsg = {
        1: 'HomeWizard url could not be reached',
        2: 'Cannot login to HomeWizard',
        3: 'Connection to HomeWizard was lost',
        4: 'Not logged in to any HomeWizard'
    }

    data = {
        'status': 'failed_hydra',
        'error': error,
        'errorMessage': errorMsg[error],
        'request': {
            'route': msg.topic.replace(homewizardBaseTopic, "")
        }
    }
    string = json.dumps(data)
    client.publish(
        homewizardBaseReturnTopic + msg.topic.replace(homewizardBaseTopic, ""),
        string, BASE_QOS)
Ejemplo n.º 14
0
def on_message(client, userdata, msg):
    global msg_at_boot
    print((msg.topic+":"+str(msg.payload)+":\n"))
    if msg.topic == "Door/open":
        print(msg.topic)
        if(msg_at_boot == 1) :
           print("skipping first message at boot")
           msg_at_boot = 0
           return
        if msg.payload == b'2':
           print("trigger external door")
           GPIO.output(door1Pin, GPIO.LOW)
           time.sleep(0.5)
           GPIO.output(door1Pin, GPIO.HIGH)
        if msg.payload == b'3':
           print("trigger auto close external door")
           GPIO.output(door1Pin, GPIO.LOW)
           time.sleep(1)
           GPIO.output(door1Pin, GPIO.HIGH)
           time.sleep(60)
           GPIO.output(door1Pin, GPIO.LOW)
           time.sleep(1)
           GPIO.output(door1Pin, GPIO.HIGH)	
           client.publish("Door/open", payload=0, qos=0, retain=True)
        if msg.payload == b'12':
           print("trigger external door")
           GPIO.output(door2Pin, GPIO.LOW)
           time.sleep(1)
           GPIO.output(door2Pin, GPIO.HIGH)
        if msg.payload == b'13':
           print("trigger auto close external door")
           GPIO.output(door2Pin, GPIO.LOW)
           time.sleep(1)
           GPIO.output(door2Pin, GPIO.HIGH)
           time.sleep(60)
           GPIO.output(door2Pin, GPIO.LOW)
           time.sleep(1)
           GPIO.output(door2Pin, GPIO.HIGH)	
           client.publish("Door/open", payload=0, qos=0, retain=True)
        '<s:Envelope ' \
        'xmlns:s="http://schemas.xmlsoap.org/soap/envelope/"' \
        's:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">' \
        '<s:Body>' \
        '<u:GetInsightParams xmlns:u="urn:Belkin:service:insight:1"></u:GetInsightParams>' \
        '</s:Body>' \
        '</s:Envelope>'

conn = http.client.HTTPConnection(ipAddress, 49154)
conn.request("POST", "/upnp/control/insight1", data2, headers)
response = conn.getresponse()
resp_data = response.read()

if response.status == 200:
    conn.close()
    power_data_collections = ElementTree.fromstring(
        resp_data.decode()).find('.//InsightParams').text.split("|")

    client = mqtt.Client()
    client.username_pw_set('xpimatpq', 'r512yUWDQJO9')
    client.connect('10.112.10.127', 50844, 2)

    payload = {
        'time': datetime.now().timestamp(),
        'current_power': power_data_collections[7],
    }
    client.publish('power_usage', json.dumps(payload))
elif response.status == 403:
    print("ERROR: 403 (FORBIDDEN)")
else:
    print("ERROR: " + str(response.status))
Ejemplo n.º 16
0
def czytaj():
    # główna pętla odczytująca status Hapcana z bramki LAN
    proto = socket.getprotobyname('tcp')
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM, proto)

    headers = {
        "Content-type": "application/x-www-form-urlencoded",
        "Accept": "text/plain"
    }
    conn = http.client.HTTPConnection("api.thingspeak.com:80")

    try:
        # 8. Ip i port modulu HAPCAN ethernet
        sock.connect(("192.168.1.1", 1002))

        while True:
            #resp = bytearray()
            resp = sock.recv(1)
            # teraz sprawdzi czy początek odebranego ciągu to początek ramki
            if resp[0] == 0xaa:
                # pobranie pozostałej części ramki
                for i in range(14):
                    resp += sock.recv(1)
                # sprawdzenie sumy kontrolnej
                if hap_crc(resp) == resp[13]:
                    modul = resp[3]
                    grupa = resp[4]
                    id_urzadzenia = resp[7]
                    stan = resp[8]
                    if resp[1] == 0x30:  #rozkaz stanu
                        #print("Rozkaz stanu", "to hex",toHex(resp[2]))
                        if resp[2] == 0x00:  # ramka czasu
                            print("Ramka czasu", toHex(resp[3]),
                                  toHex(resp[4]))
                            czas_pracy = OKRES_CZASU.get(3)
                            czas_pracy = czas_pracy + 1
                            OKRES_CZASU[3] = czas_pracy
                        if resp[2] == 0x20 or resp[
                                2] == 0x21:  # ramka przekaźnika
                            komendy = MAPOWANIE_HAP.get(
                                (modul, grupa, id_urzadzenia), None)
                            if komendy is not None:
                                idx = komendy['idx']
                                nazwa = komendy['nazwa']
                                print("Stan switcha", nazwa, " ",
                                      str(stan & 1))
                                komenda = '{"idx": ' + str(
                                    idx) + ', "nvalue" : ' + str(
                                        stan & 1) + ', "svalue" : "0"}'
                                IGNOROWANIE[idx] = IGNOROWANIE.get(idx, 0) + 1
                                client.publish("domoticz/in", komenda)
                            else:
                                print('Brak opisu przekaźnika !!!')

                        if resp[2] == 0x40 or resp[
                                2] == 0x41:  # ramka przycisku
                            #print("Ramka przycisku",)
                            if resp[7] == 0x11:  # ramka temperatury
                                komendy = MAPOWANIE_HAP.get(
                                    (modul, grupa, id_urzadzenia), None)
                                if komendy is not None:
                                    idx = komendy['idx']
                                    IGNOROWANIE[idx] = IGNOROWANIE.get(idx,
                                                                       0) + 1
                                    tt1 = happroc.spr_temp(resp[8], resp[9])
                                    komenda = '{"idx": ' + str(
                                        idx
                                    ) + ', "nvalue" : 0, "svalue" : "' + str(
                                        tt1) + '"}'
                                    #print("Komenda to ...",komenda)
                                    pole_th = komendy.get('pole_th', None)
                                    if pole_th is not None:
                                        print(
                                            "Temp THING to ....",
                                            tt1,
                                        )
                                        klucz_th = komendy.get(
                                            'klucz_th', None)
                                        params = urllib.parse.urlencode({
                                            pole_th:
                                            tt1,
                                            'key':
                                            klucz_th
                                        })
                                        try:
                                            conn.request(
                                                "POST", "/update", params,
                                                headers)
                                            response = conn.getresponse()
                                            data = response.read()
                                            #print('odpowiedź od Th',data)
                                        except Exception as bld:
                                            print(
                                                "connection failed z Thingiem")
                                            plik = open("errory.log",
                                                        mode="a+")
                                            plik.write(time.asctime() + ',' +
                                                       str(bld) + '\n')
                                    client.publish("domoticz/in", komenda)
                                # teraz odczyt termostatu (id_urzadzenia ustawiony na 0x14)
                                id_urzadzenia = 0x14
                                komendy = MAPOWANIE_HAP.get(
                                    (modul, grupa, id_urzadzenia), None)
                                if komendy is not None:
                                    idx = komendy['idx']
                                    IGNOROWANIE[idx] = IGNOROWANIE.get(idx,
                                                                       0) + 1
                                    tt1 = happroc.spr_temp(resp[10], resp[11])
                                    komenda = '{"idx": ' + str(
                                        idx
                                    ) + ', "nvalue" : 0, "svalue" : "' + str(
                                        tt1) + '"}'
                                    #print("Komenda to ...", komenda)
                                    client.publish("domoticz/in", komenda)

                        if resp[2] == 0x70 or resp[2] == 0x71:  # ramka rolety
                            #print("Ramka rolety", procent)
                            if FLAGI[1]:
                                map_temp = FLAGI[2]
                                nodes = map_temp.get('nodes')
                                procent = map_temp.get('procent')
                                if id_urzadzenia == nodes[2]:
                                    if resp[9] == 0:  # sprawdza czy nie jest w ruchu
                                        map_temp2 = MAPOWANIE_HAP.get(nodes)
                                        czas_rol = map_temp2.get('czas_rol')
                                        komunikat = 0x10A0
                                        dane = [
                                            0xF0, 0xF0, 0x00, 0x00, 0x00, 0x00,
                                            0x00, 0xFF, 0xFF, 0xFF
                                        ]
                                        dane[3] = 2**(nodes[2] - 1)
                                        dane[4] = nodes[0]
                                        dane[5] = nodes[1]
                                        #stan = stan / 255 * 100
                                        ile_czasu = czas_rol * (
                                            (stan / 2.55) - procent) / 100
                                        if ile_czasu < 0:
                                            dane[2] = 0x04
                                        else:
                                            dane[2] = 0x03
                                        print(
                                            "**********************************************",
                                            komunikat, "dane", dane,
                                            "; procent", procent,
                                            "; stan rolety", stan,
                                            "; ile czasu", ile_czasu)
                                        wyslij(komunikat, dane)
                                        dane[2] = 0
                                        dane[6] = int(round(abs(ile_czasu), 0))
                                        print(
                                            "**********************************************",
                                            komunikat, "dane", dane)
                                        wyslij(komunikat, dane)

                                        FLAGI[1] = 0
                        if resp[2] == 0x60 or resp[2] == 0x61:  # ramka Dimmera
                            #print("Ramka dimera nr kanału", resp[7], resp[8])
                            if resp[7] == 1:
                                proc_dimer = int((resp[8] / 255) * 100)
                                print("Żarówka na %", proc_dimer)
                                komendy = MAPOWANIE_HAP.get(
                                    (modul, grupa, id_urzadzenia), None)
                                if komendy is not None:
                                    idx = komendy['idx']
                                    nazwa = komendy['nazwa']
                                    print("Stan dimera", nazwa, " ",
                                          proc_dimer)
                                    komenda = '{"command": "switchlight", "idx": ' + str(
                                        idx
                                    ) + ', "switchcmd": "Set Level", "level": ' + str(
                                        proc_dimer) + ' }'
                                    IGNOROWANIE[idx] = IGNOROWANIE.get(idx,
                                                                       0) + 1
                                    client.publish("domoticz/in", komenda)
                                else:
                                    print('Brak opisu dimera !!!')

                            komendy = MAPOWANIE_HAP.get(
                                (modul, grupa, id_urzadzenia), None)
                            if komendy is not None:
                                idx = komendy['idx']
                                IGNOROWANIE[idx] = IGNOROWANIE.get(idx, 0) + 1
                                procent = stan / 255 * 100
                                komenda = '{"idx": ' + str(
                                    idx
                                ) + ', "nvalue" : 2, "svalue" : "' + str(
                                    procent) + '"}'
                                #print("Komenda to ...", komenda)
                                client.publish("domoticz/in", komenda)
                            # teraz tu umieszczę dalszy program :)

    except socket.error as bld:
        print("Error?")
        plik = open("errory.log", mode="a+")
        plik.write(time.asctime() + ',' + str(bld) + '\n')
    except Exception as bld:
        plik = open("errory.log", mode="a+")
        plik.write(time.asctime() + ',' + str(bld) + '\n')
        #pass
    finally:
        plik.close()
        sock.close()
        conn.close()
Ejemplo n.º 17
0
def czytaj():
    # główna pętla odczytująca status Hapcana z bramki LAN
    proto = socket.getprotobyname('tcp')
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM, proto)

    try:
        # 8. Ip i port modulu HAPCAN ethernet
        sock.connect(("192.168.1.201", 1002))

        while True:
            resp = bytearray()
            resp = sock.recv(1)
            # teraz sprawdzi czy początek odebranego ciągu to początek ramki
            if resp[0] == 0xaa:
                #print("Resp !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!",binascii.hexlify(resp) )
                for i in range(14):
                    resp += sock.recv(1)
                #print("nr 15",toHex(resp[14]))
                if hap_crc(resp) == resp[13]:
                    #print("Ramka się zgadza !!!!!!!!!!!!!!!!",binascii.hexlify(resp))
                    modul = resp[3]
                    grupa = resp[4]
                    id_urzadzenia = resp[7]
                    stan = resp[8]
                    if resp[1] == 0x30: #rozkaz stanu
                        #print("Rozkaz stanu", "to hex",toHex(resp[2]))
                        if resp[2] == 0x00: # ramka czasu
                            print("Ramka czasu",toHex(resp[3]),toHex(resp[4]) )
                            indeks_mod = OKRES_CZASU.get(1)
                            indeks_mod = indeks_mod + 1
                            komenda = MAPOWANIE_MOD.get(indeks_mod, None)
                            if komenda is not None:
                                id_komunikatu = komenda['komunikat']
                                dane = komenda['dane']
                                msg = bytearray()
                                msg.append(0xAA)
                                b2 = (id_komunikatu >> 8) & 0xFF;
                                msg.append(b2)
                                b1 = (id_komunikatu) & 0xFF;
                                msg.append(b1)
                                for val in dane:
                                    msg.append(val)
                                msg.append(hap_crc(msg))
                                msg.append(0xA5)
                                sock.sendall(msg)
                                print('wyslano =', binascii.hexlify(msg))
                                OKRES_CZASU[1] = indeks_mod
                            else:
                                OKRES_CZASU[1] = 0  # kasujemy licznik listy modułów do odczytu
                        if resp[2] == 0x20 or resp[2] == 0x21:  # ramka przekaźnika
                            #print("Ramka przekaźnika", )
                            komendy = MAPOWANIE_ETH.get((modul, grupa, id_urzadzenia), None)
                            if komendy is not None:
                                idx = komendy['idx']
                                komenda = komendy.get(stan, None)
                                if komenda is not None:
                                    IGNOROWANIE[idx] = IGNOROWANIE.get(idx, 0) + 1
                                    #print("WYSYłAMY do domoticza stan przekaźnika", komenda)
                                    client.publish("domoticz/in", komenda)

                        if resp[2] == 0x40 or resp[2] == 0x41: # ramka przycisku
                            #print("Ramka przycisku",)
                            if resp[7] == 0x11: # ramka temperatury
                                komendy = MAPOWANIE_ETH.get((modul, grupa, id_urzadzenia), None)
                                if komendy is not None:
                                    idx = komendy['idx']
                                    IGNOROWANIE[idx] = IGNOROWANIE.get(idx, 0) + 1
                                    tt1 = happroc.spr_temp(resp[8], resp[9])
                                    komenda = '{"idx": '+ str(idx) + ', "nvalue" : 0, "svalue" : "' + str(tt1) + '"}'
                                    #print("Komenda to ...",komenda)
                                    client.publish("domoticz/in", komenda)
                                # teraz odczyt termostatu (id_urzadzenia ustawiony na 0x14)
                                id_urzadzenia = 0x14
                                komendy = MAPOWANIE_ETH.get((modul, grupa, id_urzadzenia), None)
                                if komendy is not None:
                                    IGNOROWANIE[idx] = IGNOROWANIE.get(idx, 0) + 1
                                    tt1 = happroc.spr_temp(resp[10], resp[11])
                                    idx = komendy['idx']
                                    komenda = '{"idx": ' + str(idx) + ', "nvalue" : 0, "svalue" : "' + str(tt1) + '"}'
                                    #print("Komenda to ...", komenda)
                                    client.publish("domoticz/in", komenda)


                        if resp[2] == 0x70 or resp[2] == 0x71:  # ramka rolety
                            procent = stan/255*100
                            #print("Ramka rolety", procent)
                            komendy = MAPOWANIE_ETH.get((modul, grupa, id_urzadzenia), None)
                            if komendy is not None:
                                idx = komendy['idx']
                                komenda = '{"idx": ' + str(idx) + ', "nvalue" : 2, "svalue" : "' + str(procent) + '"}'
                                #print("Komenda to ...", komenda)
                                client.publish("domoticz/in", komenda)
                            # teraz tu umieszczę dalszy program :)

    except socket.error as bld:
        print("Error?")
        plik = open("errory.log", mode="a+")
        plik.write(time.asctime()+ ',' + str(bld)+ '\n')
    except Exception as bld:
        plik = open("errory.log", mode="a+")
        plik.write(time.asctime() + ',' + str(bld) + '\n')
        #pass
    finally:
        plik.close()
        sock.close()
Ejemplo n.º 18
0
def lambda_handler(event, context):
    sqs = boto3.resource('sqs')
    queue = sqs.get_queue_by_name(QueueName='DiningQueue')
    for message in queue.receive_messages():
        final_string = json.loads(message.body)
        location = final_string['Location']
        cuisine = final_string['Cuisine']
        dining_time = final_string['Dining_time']
        no_of_people = final_string['Number_of_people']
        phone_number = final_string['Phone_Number']

        message.delete()
        print('deleted')

        headers = {
            'Authorization':
            'Bearer 9zufu4z0309-nY2mBhXSm8GZEctBZGrtIoR9eqt9sxVv7h9NfBXMsNySKf1p3Y_RHF4vg3nBmBBfxS8SPqOAeIcOKNMIJQf-MQmlyUhbQxoX2dSZatl9sttTKZDnW3Yx',
        }
        client = boto3.client('dynamodb')
        dynamodb = boto3.resource('dynamodb', region_name='us-east-1')
        table = dynamodb.Table('DiningsuggestionTable')

        # try:
        conn = http.client.HTTPSConnection("api.yelp.com")
        url = "https://api.yelp.com/v3/businesses/search?term=" + str(
            cuisine) + "&location=" + str(location)
        conn.request("GET", url, headers=headers)
        response = conn.getresponse()
        data = response.read()
        data = json.loads(data.decode("utf-8"))
        restaurant_yelpdata = data["businesses"]
        restaurantList = []
        addresslist = []
        restaurantListLocation = []
        for i in range(len(restaurant_yelpdata)):
            restaurant = restaurant_yelpdata[i]
            id = restaurant['id']
            Cuisine = restaurant['categories'][0]['title']
            Rating = decimal.Decimal(restaurant['rating'])
            NumberOfReviews = restaurant['review_count']
            Zipcode = restaurant['location']['zip_code']
            name = restaurant['name']
            address = restaurant['location']['address1']
            if i < 3:
                restaurantList.append(name)
                addresslist.append(address)
                # restaurantListLocation.append(Zipcode)
            print(id, Cuisine, Rating, NumberOfReviews, Zipcode, name)
            response=table.put_item(Item={"categories":Cuisine,"id":id,"Rating":Rating,"review_count":NumberOfReviews,\
                                         "Zip Code":Zipcode,"Name":name})
            print(response)

        conn.close()

        stringToOutput = ""
        for j in range(3):
            stringToOutput += " " + restaurantList[j] + " " + addresslist[
                j] + "\n"

        string_toSend = "Hello! Here are my " + cuisine + " restaurant suggestions for " + no_of_people + " people, for " + dining_time + ": \n"
        string_toSend = string_toSend + stringToOutput
        client = boto3.client('sns')
        # client.subscribe(TopicArn = 'arn:aws:sns:us-east-1:995739821424:DiningMessages',Protocol='SMS',Endpoint=phone_number)
        client.publish(Message=string_toSend, PhoneNumber=phone_number)
Ejemplo n.º 19
0
            logging.info("PM2.5: %d" % pm2_5)
            logging.info("PM10: %d" % pm10)
        finally:
            pass

        # report to MQTT
        if mqtt_cfg["enable"] == True:
            if flag_connected == False:
                try:
                    # reconnect
                    client.connect(mqtt_server, mqtt_port, 60)
                    logging.info("MQTT reconnect triggered.")
                except:
                    logging.error("MQTT reconnect failed!")
            try:
                client.publish(sensor_name + "/Timestamp", st)
                client.publish(sensor_name + "/Temp", temp)
                client.publish(sensor_name + "/Humid", humid)
                client.publish(sensor_name + "/Temp_out", temp_out)
                client.publish(sensor_name + "/Humid_out", humid_out)
                client.publish(sensor_name + "/PM2_5", pm2_5)
                client.publish(sensor_name + "/PM10", pm10)
            except:
                logging.error("MQTT communication error!")
                traceback.print_exec()

        # report to MySQL
        if mysql_cfg["enable"] == True:
            mysql_commit(sensor_id, temp, humid, temp_out, humid_out,
                         mysql_cfg)
Ejemplo n.º 20
0
def update_cerradura():
    password = request.json['password']
    posicion = request.json['posicion']
    nuevo_candado = "1;" + password + ";" + posicion
    client.publish(topico, nuevo_candado)
    return jsonify(nuevo_candado)
Ejemplo n.º 21
0
def process_message(client, msg, attempt):
    global homewizardBaseUrl
    global reconnectThread

    # Fail 3: Several attempts failed, just end here
    if (attempt > 3):
        print(get_time_string(), "Hit attempt limit for message at", msg.topic,
              str(msg.payload))
        publish_fail_msg(client, msg, 3)
        return

    try:
        # url consists of topic plus payload. Keep this in mind when sending messages. Slash is added between payload and topic.
        url = homewizardBaseUrl + msg.topic.replace(
            homewizardBaseTopic, "") + "/" + msg.payload.decode("utf-8")
        response = urllib.request.urlopen(url)
    except urllib.request.URLError:
        # Fail 1: Can not reach url
        print(get_time_string(), "HomeWizard url could not be reached for",
              msg.topic, str(msg.payload))
        publish_fail_msg(client, msg, 1)
    except http.client.RemoteDisconnected as e:
        print(get_time_string(), e)
        publish_fail_msg(client, msg, 3)
    else:
        # Publish result on base return topic with same topic as incoming message
        print(get_time_string(), "Processed message for HomeWizard at",
              msg.topic, str(msg.payload))
        result = response.read().decode("utf-8")
        jsonData = json.loads(result)

        if (jsonData["status"] == "failed"):
            if "errorMessage" not in jsonData:
                # Testing shows this is porbably a bad URL, not a connection error
                # We should publish the response anyway
                # TODO: More testing
                print(get_time_string(), "Failed request at", msg.topic,
                      str(msg.payload), "with error", jsonData["error"])
                client.publish(
                    homewizardBaseReturnTopic +
                    msg.topic.replace(homewizardBaseTopic, ""), result,
                    BASE_QOS)
            else:
                # Probably a connection error, try to reconnect
                print(get_time_string(), "Failed request at", msg.topic,
                      str(msg.payload), "with error", jsonData["error"],
                      jsonData["errorMessage"])

                # Wait until reconnect is finished
                if ((reconnectThread is None)
                        or (reconnectThread.is_alive() == False)):
                    reconnectThread = threading.Thread(
                        target=homewizard_reconnect)
                    reconnectThread.start()
                    # Give reconnectThread time to start
                    time.sleep(0.1)
                reconnectThread.join()

                if homewizardBaseUrl is None:
                    # Fail 2: Can't reconnect
                    print(get_time_string(),
                          "Could not reconnect to HomeWizard")
                    publish_fail_msg(client, msg, 2)
                else:
                    # Try again after the reconnect
                    print(get_time_string(),
                          "Reconnected to HomeWizard at attempt", attempt,
                          ", retrying message")
                    process_message(client, msg, attempt + 1)
        else:
            client.publish(
                homewizardBaseReturnTopic +
                msg.topic.replace(homewizardBaseTopic, ""), result, BASE_QOS)
Ejemplo n.º 22
0
def process_hue_message(client, msg):
    action = msg.topic.rsplit('/', 1)[1]  # Last part of topic is the action
    if (action == "connect"):
        print("Processing HUE connect message")
        hue_connect(msg.payload.decode("utf-8"))  # Connect to a Hue bridge
        return
    if (hueBridge is not None):
        print("Processing HUE message")
        print(msg.payload.decode("utf-8"))
        if (action == "get-lights"):
            try:
                lights = hueBridge.get_light_objects(
                    "id")  # Get Hue lights data
            except Exception as e:
                print("Error on HUE get-lights")
            else:
                lightData = []
                for index in lights:
                    l = lights[index]
                    # Make a nice package of the light's status
                    # TODO: Add proper support for other light types
                    if (l.type == "Extended color light"):
                        ld = {
                            "name": l.name,
                            "id": index,
                            "type": l.type,
                            "on": l.on,
                            "colormode": l.colormode,
                            "brightness": l.brightness,
                            "hue": l.hue,
                            "saturation": l.saturation,
                            "xy": l.xy,
                            "colortemp": l.colortemp
                        }
                    else:
                        ld = {
                            "name": l.name,
                            "id": index,
                            "type": l.type,
                            "on": l.on,
                            "brightness": l.brightness
                        }
                    lightData.append(ld)
                jsonData = json.dumps(lightData)
                client.publish(hueBaseReturnTopic + "/" + action, jsonData)
        elif (
                action == "set-light"
        ):  # Payload has to be a json string containing first and second param
            try:  # hueBridge.set_light(lights, command)
                jsonData = json.loads(msg.payload.decode("utf-8"))
                lights = jsonData["lights"]
                command = jsonData["command"]

                hueBridge.set_light(lights, command)
            except Exception as e:
                print("Error on HUE set-light payload")
        elif (
                action == "set-name"
        ):  # Payload has to be a json object with light (id) and name (new name)
            try:
                jsonData = json.loads(msg.payload.decode("utf-8"))
                light = jsonData["light"]
                name = jsonData["name"]

                hueBridge.set_light(light, "name", name)
            except Exception as e:
                print("Error on HUE set-name payload")
    else:
        # Not connected to HUE
        print("Processing HUE message, but no Hue")
        errorData = {
            "status": "hydra_failed",
            "error": 99,
            "errorMessage": "Not connected to Hue bridge",
            "request": {
                "route": action
            }
        }
        client.publish(hueBaseReturnTopic + "/" + action,
                       json.dumps(errorData))
Ejemplo n.º 23
0
def delete_clave_cerradura():
    posicion = request.json['posicion']
    nuevo_candado = "2;" + posicion
    client.publish(topico, nuevo_candado)
    return jsonify(nuevo_candado)
Ejemplo n.º 24
0
def process_auth_request(client, msg):
    global homewizardBaseUrl
    global reconnectThread
    global connectAuthThread

    global username
    global password

    # Wait for a reconnect if there is any running to prevent race conditions
    if ((reconnectThread is not None) and (reconnectThread.is_alive())):
        reconnectThread.join()
    reconnectThread = threading.current_thread()

    try:
        loginData = json.loads(msg.payload.decode("utf-8"))

        if (loginData["type"] == "login"):
            print(get_time_string(),
                  "Recieved connection request for HomeWizard")
            if homewizardBaseUrl is None:
                urlResult = homewizard_connect(loginData["email"],
                                               loginData["password"], False)
                if urlResult is None:
                    print(get_time_string(), "Could not connect to HomeWizard")
                    publish_auth_fail_msg(client, 70)
                else:
                    # Publish result
                    data = {
                        'status': 'ok',
                        'request': {
                            'route': 'hydralogin'
                        },
                        'serial': get_serial(urlResult)
                    }
                    string = json.dumps(data)
                    client.publish(hydraAuthTopic + "/results", string,
                                   BASE_QOS)

                    # Update globals
                    homewizardBaseUrl = urlResult
                    username = loginData["email"]
                    password = loginData["password"]
            else:
                print(get_time_string(), "Already connected to HomeWizard!")
                publish_auth_fail_msg(client, 72)

        elif (loginData["type"] == "disconnect"):
            print(get_time_string(),
                  "Recieved disconnect request for HomeWizard")
            client.publish(
                hydraAuthTopic + "/results",
                json.dumps({
                    'status': 'ok',
                    'request': {
                        'route': 'hydradisconnect'
                    },
                    'serial': ''
                }))
            homewizardBaseUrl = None
        else:
            print(get_time_string(), "Invalid login payload")
            publish_auth_fail_msg(client, 71)
    except:
        print(get_time_string(), "Invalid login payload")
        publish_auth_fail_msg(client, 71)
Ejemplo n.º 25
0
def delete_all_cerraduras():
    mensaje = "3"
    client.publish(topico, mensaje)
    return jsonify(mensaje)
Ejemplo n.º 26
0
import datetime
import time
import os
datecount = 0
dateincreament = 7

mqttaddress = os.getenv('mqttaddress', '192.168.1.11')
print("mqttaddress env value", mqttaddress)
mqttport = os.getenv('mqttport', '1883')
print("mqttport env value", mqttport)
discord = os.getenv('discord', 'aaa')
print("discord env value", discord)

client = mqtt.Client()
client.connect(mqttaddress, int(mqttport))
client.publish("topic/vaccine_status", "no", retain=True)
webhook = Webhook.from_url(discord, adapter=RequestsWebhookAdapter())

while True:
    if datecount == 0:
        x = datetime.datetime.now()
        date1 = x.strftime("%d-%m-%Y")
        datecount = datecount + 1
    elif datecount == 3:
        dateincreament = 7
        datecount = 0
        print("\n sleeping for 5min \n")
        time.sleep(300)
        client.disconnect()
        client.connect(mqttaddress, int(mqttport))
        continue
Ejemplo n.º 27
0
def on_message(client, userdata, msg):
    global deck_state
    print((msg.topic+" "+str(msg.payload)+"\n"))
#    if msg.topic == "Door/open":
#        print msg.topic
    if msg.payload == b'3151714':
        print("Switch 1 trigger received")
        print("trigger external door")
        client.publish("Door/open", payload='2', qos=1, retain=False)

#Dorian
    if msg.payload == b'6454993':
        print("Remote 1 A trigger received")
        print("trigger external door")
        client.publish("Door/open", payload='12', qos=1, retain=False)
	#getImageFromCamera2();
        getImageFromCamera1();
        time.sleep(1)
        client.publish("Door/dorian", payload='Portail Dorian', qos=1, retain=False)

    if msg.payload == b'6454994':
        print("Remote 1 B trigger received")
        print("trigger external door")
        client.publish("Door/open", payload='2', qos=1, retain=False)
        getImageFromCamera1();
        time.sleep(1)
        client.publish("Door/dorian", payload='Portail Dorian', qos=1, retain=False)
	
#Gael
    if msg.payload == b'14993777':
        print("Remote 2 A trigger received")
        print("trigger external door")
        client.publish("Door/open", payload='12', qos=1, retain=False)
	#getImageFromCamera2();
        getImageFromCamera1();
        time.sleep(1)
        client.publish("Door/gael", payload='Portail Gael', qos=1, retain=False)

    if msg.payload == b'14993778':
        print("Remote 2 B trigger received")
        print("trigger external door")
        client.publish("Door/open", payload='2', qos=1, retain=False)
        time.sleep(1)
        getImageFromCamera1();
        client.publish("Door/gael", payload='Portail Gael', qos=1, retain=False)

    if msg.payload == b'16276098':
        print("Door bell trigger received")
        print("trigger Ring")
        getImageFromCamera1();
        time.sleep(1)
        client.publish("Door/bell", payload='1', qos=1, retain=False)
		
    if msg.payload == b'14786398':
        print("Move trigger received")
        print("trigger move")
        client.publish("move/detected", payload='1', qos=1, retain=False)




    if msg.payload == b'10867362':
        print("Switch 2 trigger received")
        print("trigger Deck light")
        if(deck_state == 1):
           newValue   = '1'
           deck_state = 0
        else:
           newValue   = '2'
           deck_state = 1
	   	
        client.publish("DECK_LEDS/stairs", payload=newValue, qos=1, retain=False)
        client.publish("DECK/LIGHT/command", payload=newValue, qos=1, retain=False)
Ejemplo n.º 28
0
    #print("Connected with result code "+str(rc))

    # Subscribing in on_connect() means that if we lose the connection and
    # reconnect then subscriptions will be renewed.
    client.subscribe("/door/front/mode")
    client.subscribe("/door/front/add")
    client.subscribe("/door/front/status")


db = Database()

client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message
## Clears any retained messages on the mode channel, eliminates triggering a door open on boot and removes any retained message from clients
client.publish("/door/front/mode", "Clear", retain=True)

client.connect("192.168.68.112", 1883, 60)
client.loop_start()

GPIO.setmode(GPIO.BOARD)  # Use physical pin numbering
GPIO.setup(7, GPIO.IN, pull_up_down=GPIO.PUD_UP)

Alert("Door Lock Started")
while (end_Thread == 0):
    input_state = GPIO.input(7)

    if (input_state == False):

        mode = db.fetch("mode")
Ejemplo n.º 29
0
#        ti = np.concatenate(ti, axis=0); ti[(ti<-55) | (ti>125)] = np.nan
#        tsi = np.concatenate(tsi, axis=0); tsi[(tsi<-55) | (tsi>125)] = np.nan
#        te = np.concatenate(te, axis=0); te[(te<-55) | (te>125)] = np.nan
#
#        # Calculamos a media de cada sensor para o tempo dado
#        ti = ti[~np.isnan(ti)].mean(); tsi = tsi[~np.isnan(tsi)].mean(); te = te[~np.isnan(te)].mean()
#
#        U = hsi * (ti - tsi) / (ti - te)
#        U = np.around(U, decimals=2)
#    except ValueError:
#        U = None
#    return(U)

if __name__ == "__main__":
    logger.debug('Empeza o script')
    client = mqtt.Client()
    client.on_connect = on_connect
    client.on_message = on_message
    client.connect("192.168.3.1", 1883, 60)
    client.publish(xestion['ordes'],
                   'pausar')  # Estado a Off. Agardamos sinal de On
    client.publish(difMinimaTemp['difMinima'], '15.0')
    #    client.connect("iot.eclipse.org", 1883, 60)

    #    client.loop_start()  #Mellor loop_start, proporciona un fio non bloqueante
    #    client.loop_forever() #loop_forever proporciona un fío bloqueante
    while True:
        client.loop(16)
        t.sleep(1)
    logger.debug('Remata o script')