Exemplo n.º 1
0
def main():

    i = 0

    app_id = "radhemicrochip"
    access_key = "ttn-account-v2.anvcRy7edUgm8sQuhWfd4YXBCq6X6c2BFU54fgSm5E8"

    handler = ttn.HandlerClient(app_id, access_key)

    # using mqtt client
    mqtt_client = handler.data()
    mqtt_client.set_uplink_callback(uplink_callback)

    # using application manager client
    #app_client =  handler.application()
    #my_app = app_client.get()
    #print(my_app)
    #my_devices = app_client.devices()
    #print(my_devices)

    while(True):
        i = i + 1
        print("Sending request number (%d)" % i)
        send_ttn_request(mqtt_client)

    conn.close()
Exemplo n.º 2
0
def connectToTTN():
    logging.info("Connecting to TTN broker")
    handler = ttn.HandlerClient(app_id, access_key)
    ttnClient = handler.data()
    ttnClient.set_uplink_callback(ttn_callback)
    ttnClient.connect()
    logging.info("Connected to TTN broker")
Exemplo n.º 3
0
def main(config, block=False):
    """
    Set up a TTN pubsub connection and register a callback. If
    block is True, the function will enter into a sleeping
    infinite loop.
    """
    app_id = config["TTN_APP_ID"]
    access_key = config["TTN_APP_ACCESS_KEY"]
    assert app_id is not None
    assert access_key is not None
    handler = ttn.HandlerClient(app_id, access_key)

    logging.info(f"setting up client for {app_id}")
    mqtt_client = handler.data()
    mqtt_client.set_uplink_callback(uplink_callback)

    if not block:
        return mqtt_client

    logging.info("connecting MQTT client")
    try:
        mqtt_client.connect()
        logging.info("waiting on new connections")
        while True:
            time.sleep(1)
    except KeyboardInterrupt:
        logging.info("keyboard interrupt caught, exiting")
        return None
    except Exception as exc:
        logging.exception(exc)
    finally:
        logging.info("closing existing MQTT client")
        mqtt_client.close()
Exemplo n.º 4
0
    def __init__(self, app_id, access_key):
        handler = ttn.HandlerClient(app_id, access_key)

        # using mqtt client
        mqtt_client = handler.data()
        mqtt_client.set_uplink_callback(TTNMQTTClient.uplink_callback)
        mqtt_client.connect()
Exemplo n.º 5
0
def main():

    i = 0

    app_id = "microchipuno"
    access_key = "ttn-account-v2.Y3Sk5dTSbvnYEd3xpts99kuURsBUzTuE8iFhUJCvPfQ"

    handler = ttn.HandlerClient(app_id, access_key)

    # using mqtt client
    mqtt_client = handler.data()
    mqtt_client.set_uplink_callback(uplink_callback)

    # using application manager client
    #app_client =  handler.application()
    #my_app = app_client.get()
    #print(my_app)
    #my_devices = app_client.devices()
    #print(my_devices)

    while (True):
        i = i + 1
        print("Sending request number (%d)" % i)
        send_ttn_request(mqtt_client)

    conn.close()
Exemplo n.º 6
0
def main():
    ini_file_path = "../../config/temp-sensors.ini"
    # The configuration file path will become a command-line argument
    config = configparser.ConfigParser()
    config.read(ini_file_path)
    connection = config['ttn-explore.mqtt.connection']
    app_id = connection['username']  # This is the Application ID for this integration at TTN
    access_key = connection['password']  # This is the my-python-client application access key

    def uplink_callback(msg, client):
        print("Received uplink from ", msg.dev_id)
        print(msg)

    print("Making the TTN handler")
    handler = ttn.HandlerClient(app_id, access_key)

    print("Get data using mqtt client")
    # using mqtt client
    mqtt_client = handler.data()  # type: MQTTClient
    mqtt_client.set_uplink_callback(uplink_callback)
    print("Connecting....")
    mqtt_client.connect()
    wait_seconds = 60 * 60 * 24
    print(f"Now wait for {wait_seconds} seconds after connect")
    while True:
      time.sleep(600)
      print("Continue polling...")
    print("Close the client")
    mqtt_client.close()
Exemplo n.º 7
0
    def __init__(self, app_id, access_key):
        logging.debug("app id: {}".format(app_id))

        ttnHandler = ttn.HandlerClient(app_id, access_key)
        self._mqtt_client = ttnHandler.data()

        def _uplink_callback(message, client):
            logging.debug("uplink message received from {}".format(
                message.dev_id))
            logging.debug(str(message))

            if not message.payload_raw:
                logging.warning("message without payload, skipping...")
                return

            try:
                payload = base64.b64decode(message.payload_raw)
                logging.debug("payload: {}".format(payload.hex('-').upper()))

                device_id = bytes.fromhex(message.hardware_serial)
                logging.debug("device_id: {}".format(device_id.hex()))

                self._handle_message(payload, device_id, message)

            except Exception as e:
                logging.error(
                    "exception during message handling: {}".format(e))
                logging.error(traceback.format_exc())

        self._mqtt_client.set_uplink_callback(_uplink_callback)
Exemplo n.º 8
0
def main():
    if os.path.isfile(f_secrets):
        with open(f_secrets, "r") as f:
            secrets = json.loads(f.read())
            app_id = secrets['app_id']
            app_key = secrets['app_key']
    else:
        print("cannot find file with APP ID and KEY")
        exit(1)

    print("APP ID: ", app_id)
    print("APP KEY:", app_key)

    if os.path.isfile(f_tracker):
        with open(f_tracker, "r") as f:
            global dev_urls
            dev_urls = json.loads(f.read())

    print("URLS: ", json.dumps(dev_urls, indent=2))
    with open(f_logging, 'a') as fl:
        print(json.dumps(dev_urls), file=fl)

    ttncli = ttn.HandlerClient(app_id, app_key)

    mqttcli = ttncli.data()
    mqttcli.set_uplink_callback(uplink_callback)
    mqttcli.connect()

    while 1:
        time.sleep(10)
Exemplo n.º 9
0
    def initTTNclient(self):
        self.app_id = 'assignment'
        self.access_key = 'ttn-account-v2.tJXg3gyYmMBzO4lELeFiL1uOVghBvaJb_c9ncAG-wPA'

        handler = ttn.HandlerClient(self.app_id, self.access_key)

        self.mqtt_client = handler.data()
        self.mqtt_client.set_uplink_callback(self.uplink_callback)
        self.mqtt_client.connect()
Exemplo n.º 10
0
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('secrets',
                        type=str,
                        help="JSON file with secrets for TTN and KeyCloak.")
    parser.add_argument('datastreams',
                        type=str,
                        help="JSON file with OGC datastream URLs.")
    args = parser.parse_args()

    with open(args.secrets, "r") as f:
        secrets = json.loads(f.read())

    # create auth stuff
    if 'keycloak' in secrets:
        kc = secrets['keycloak']
        rt = ''
        if os.path.isfile(f_refresh_token):
            with open(f_refresh_token, "r") as rtf:
                rt = rtf.readlines()
        if len(rt) == 0:
            rt = get_refresh_token(kc['url'], kc['id_client'], kc['id_secret'],
                                   kc['username'], kc['password'])
            with open(f_refresh_token, "w") as rtf:
                rtf.write(rt)
        at = get_access_token(kc['url'], kc['id_client'], kc['id_secret'], rt)
        global auth_header
        auth_header = get_auth_header(at)
        logging.debug("AUTH HEADER: %s", json.dumps(auth_header))
    else:
        logging.warn("No KeyCloak credentials found, skipping ...")

    if 'ttn' not in secrets:
        logging.critical("No TTN credentials found!")
        exit(1)

    with open(args.datastreams, "r") as f:
        global datastreams
        datastreams = json.loads(f.read())

    logging.debug("URLS: %s", json.dumps(datastreams, indent=2))
    with open(f_logging, 'a') as fl:
        print(json.dumps(datastreams), file=fl)

    # connect to TTN
    ttncli = ttn.HandlerClient(secrets['ttn']['app_id'],
                               secrets['ttn']['app_key'])

    mqttcli = ttncli.data()
    mqttcli.set_uplink_callback(uplink_callback)
    mqttcli.connect()

    # keep program alive and wait for uplink callbacks
    while 1:
        sleep(10)
Exemplo n.º 11
0
    def connect(self):
        print('Connecting to TTN MQTT broker')
        handler = ttn.HandlerClient(self.app_id, self.access_key)

        # Start MQTT client and wire event callbacks.
        mqtt_client = self.mqtt_client = handler.data()
        mqtt_client._MQTTClient__client.enable_logger()
        mqtt_client.set_connect_callback(self.connect_callback)
        mqtt_client.set_close_callback(self.disconnect_callback)
        mqtt_client.set_uplink_callback(self.uplink_callback)
        mqtt_client.connect()
Exemplo n.º 12
0
    def __init__(self, conn_obj):

        self.app_id =  conn_obj["app_id"]
        self.access_key = conn_obj["access_key"]
        self.device_id = conn_obj["device_id"]
        self.msg_queue = queue.Queue()

        self.handler = ttn.HandlerClient(self.app_id, self.access_key)
        self.mqtt_client = self.handler.data()
        self.mqtt_client.set_uplink_callback(self.__uplink_callback)
        self.mqtt_client.set_connect_callback(self.__connect_callback)
Exemplo n.º 13
0
def func1():
    while (True):
        print("-----func1 opn------------")
        handler = ttn.HandlerClient(app_id, access_key)
        mqtt_client = handler.data()
        mqtt_client.set_uplink_callback(uplink_callback)
        mqtt_client.connect()
        time.sleep(28800)

        mqtt_client.close()
        print("-----func1 close------------")
Exemplo n.º 14
0
    def uplink_listener(self):
        print("Uplink listener is running...")
        app_id = "geoloracja"
        access_key = "ttn-account-v2.cxnYXM8WxBx65iUHiI8KqNcpFFmGKtud5jEU-TtaiAo"
        handler = ttn.HandlerClient(app_id, access_key)

        while True:
            client = handler.data()
            client.set_uplink_callback(self.uplink_callback)
            client.connect()
            sleep(self.delay)
            client.close()
Exemplo n.º 15
0
def ttn_connect():
    handler = ttn.HandlerClient(app_id, access_key)

    # using mqtt client
    mqtt_client = handler.data()
    mqtt_client.set_uplink_callback(uplink_callback)
    mqtt_client.connect()
    print("Connect to ttn!")

    a = 0
    while (True):
        a += 1
Exemplo n.º 16
0
    def __init__(self, message_received_callback):
        app_id = "iot_arnaudaymeric_2020"
        access_key = "ttn-account-v2.2ZR7Kvt7lkJEVqDmK9QF4RCgsCX3DAmFTB7i8Oysu64"

        handler = ttn.HandlerClient(app_id, access_key)

        self.app_client = handler.application()
        self.mqtt_client = handler.data()
        self.mqtt_client.set_uplink_callback(message_received_callback)
        self.mqtt_client.set_connect_callback(connect_callback)
        self.mqtt_client.set_downlink_callback(downlink_callback)

        print(self.app_client.get())
Exemplo n.º 17
0
def mqtt_get_data():
    print("Starting")
    with open('./config.json') as json_data:
        config = json.load(json_data)
        print(config['app_id'])
        print(config['access_key'])
    handler = ttn.HandlerClient(config['app_id'], config['access_key'])
    # using mqtt client
    mqtt_client = handler.data()
    mqtt_client.set_uplink_callback(uplink_callback)
    mqtt_client.connect()
    while True:
        time.sleep(60)
Exemplo n.º 18
0
def downlink(deviceName):
    if not session.get('loggedIn'):
        return redirect(url_for('login'))
    else:
        app_id = "geoloracja"
        access_key = "ttn-account-v2.cxnYXM8WxBx65iUHiI8KqNcpFFmGKtud5jEU-TtaiAo"
        handler = ttn.HandlerClient(app_id, access_key)
        client = handler.data()
        client.connect()
        client.send(deviceName, "AQ==")
        client.close()
        flash(u'Wysłano zapytanie o obecną lokalizację')
        return redirect(url_for('mydevices'))
Exemplo n.º 19
0
    def run(self):
        handler = ttn.HandlerClient(self.app_id, self.access_key)

        # using mqtt client
        mqtt_client = handler.data()
        mqtt_client.set_uplink_callback(self.uplink_callback)
        logger.info(f"Start listening on '{self.app_id}'")
        mqtt_client.connect()
        try:
            while True:
                time.sleep(10)
        except KeyboardInterrupt:
            logger.info("Closing MQTT client")
            mqtt_client.close()
    def initMQTTclientTTN(self):
        path = "../keys/"
        values = MQTTClient.readFromCSVFile(path + "TTNkeys.txt")
        self.app_id = values["appID"]
        self.access_key = values["accessKey"]
        self.cert_file = values["certFile"]

        handler = ttn.HandlerClient(self.app_id,
                                    self.access_key,
                                    cert_path=path + self.cert_file)

        self.mqtt_client = handler.data()
        self.mqtt_client.set_uplink_callback(self.uplink_callback)
        self.mqtt_client.connect()
Exemplo n.º 21
0
def run(app_id, access_key):
    logger.info(f"Start client on '{app_id}'\n")
    handler = ttn.HandlerClient(app_id, access_key)
    
    # using mqtt client
    mqtt_client = handler.data()
    mqtt_client.set_uplink_callback(uplink_callback)
    mqtt_client.connect()
    try:
        while True:
            time.sleep(10)
    except KeyboardInterrupt:
        logger.info("Closing client, bye")
        mqtt_client.close()
Exemplo n.º 22
0
    def app_connect(self):
        def uplink_callback(msg, client):
            print()
            print("Received uplink from ", msg.dev_id)
            msg_dict = dictify(msg)
            print(msg_dict)
            # forward msg into queue
            # self.q.put(msg_dict)

        self.handler = ttn.HandlerClient(self.ttn_app_id, self.ttn_key)

        self.mqtt_client = self.handler.data()
        self.mqtt_client.set_uplink_callback(uplink_callback)
        self.mqtt_client.connect()
Exemplo n.º 23
0
def send_downlink(device_id, msg):
    '''
    Send a downlink to a device.
    '''
    handler = ttn.HandlerClient(app_id, access_key)
    mqtt_client = handler.data()
    mqtt_client.connect()
    mqtt_client.send(dev_id=device_id,
                     pay=msg,
                     port=1,
                     conf=False,
                     sched="replace")
    mqtt_client.close()
    print("[DEBUG] Downlink " + str(msg) + " has been sent to device '" +
          device_id + "'")
Exemplo n.º 24
0
    def fetch(self):
        def uplink_callback(msg, client):
            format_date = datetime.strptime(msg.metadata.time[:-5],
                                            '%Y-%m-%dT%H:%M:%S.%f')
            self.storeInput('TTN', msg.dev_id, msg.payload_fields.wifi,
                            format_date.timestamp())

        handler = ttn.HandlerClient(self.app_id, self.access_key)

        mqtt_client = handler.data()
        mqtt_client.set_uplink_callback(uplink_callback)

        while True:
            mqtt_client.connect()
            time.sleep(60)
            mqtt_client.close()
Exemplo n.º 25
0
def main():
    args = get_args()
    logging.basicConfig(level=logging.DEBUG if args.verbose else logging.INFO)

    # Connect to application API
    handler = ttn.HandlerClient(app_id=args.app_id,
                                app_access_key=args.access_key)
    app = handler.application()

    # List Devices
    # https://github.com/TheThingsNetwork/api/blob/master/handler/handler.proto#L91
    for device in app.devices():
        LOGGER.info("Device '%s'", device.dev_id)

        print(device_to_site(device, app_id=args.app_id))
        print(device_to_sensor(device, app_id=args.app_id))
Exemplo n.º 26
0
def register_device_in_ttn(app_id, access_key_file, app_eui, device_eui):
    """Register Clair TTN nodes in the TTN.

    \b
    APP_ID is the TTN application id.
    ACCESS_KEY_FILE is the file that contains the access key of the TTN application.
    APP_EUI is the TTN app EUI.
    DEVICE_EUI is the TTN device EUI.
    """

    access_key = access_key_file.read().rstrip('\n')
    application_client = ttn.HandlerClient(app_id, access_key).application()

    for dev_eui in device_eui:
        device_id = str(ers.ErsDeviceUUID(bytes.fromhex(dev_eui)))
        ttn_device = _create_ttn_device(dev_eui, app_eui)

        application_client.register_device(device_id, ttn_device)
Exemplo n.º 27
0
def main():
    """Config"""
    getConfiguration()
    """TTN"""
    handler = ttn.HandlerClient(ttn_app_id, ttn_access_key)
    # using mqtt client
    mqtt_client = handler.data()
    mqtt_client.set_uplink_callback(ttn_uplink_callback)
    mqtt_client.connect()
    """Telegram"""
    # Create the Updater and pass it your bot's token.
    updater = telegram.ext.Updater(telegram_token)
    dispatcher = updater.dispatcher
    dispatcher.add_handler(CommandHandler("start", sendLastLocation))
    dispatcher.add_handler(CommandHandler("pos", sendLastLocation))
    dispatcher.add_handler(CommandHandler("live", sendLiveLocation))
    dispatcher.add_handler(CommandHandler("stats", sendStats))
    dispatcher.add_handler(CommandHandler("watch", sendWatchdog))
    updater.start_polling()

    updater.idle()
Exemplo n.º 28
0
def main():
    ini_file_path = "../../config/temp-sensors.ini"
    # The configuration file path will become a command-line argument
    config = configparser.ConfigParser()
    config.read(ini_file_path)
    connection = config['ttn-explore.mqtt.connection']
    app_id = connection['username']  # This is the Application ID for this integration at TTN
    access_key = connection['password']  # This is the my-python-client application access key

    def uplink_callback(msg, client):
        print("Received uplink from ", msg.dev_id)
        print(msg)

    print("Making the TTN handler")
    handler = ttn.HandlerClient(app_id, access_key)

    print("Get data using mqtt client")
    # using mqtt client
    mqtt_client = handler.data()
    mqtt_client.set_uplink_callback(uplink_callback)
    print("Connecting....")
    mqtt_client.connect()
    WAIT_SECONDS = 20
    print(f"Now wait for {WAIT_SECONDS} seconds after connect")
    time.sleep(WAIT_SECONDS)
    print("Close the client")
    mqtt_client.close()

    # using application manager client
    print("Get data using application manager client")
    app_client = handler.application()
    print("Got client, now get the application")
    my_app = app_client.get()
    print(my_app)
    print("Now get a list of my devices")
    my_devices = app_client.devices()
    print(my_devices)
Exemplo n.º 29
0
def main():

    print("Transparent bridge starting...")

    # Configuring TTN broker
    app_id = config.MQTT_TTN_USER
    access_key = config.MQTT_TTN_PASS

    handler = ttn.HandlerClient(app_id, access_key)
    mqtt_client = handler.data()

    # Setting callback
    mqtt_client.set_uplink_callback(uplink_callback)
    # Connect
    mqtt_client.connect()

    print("Connection completed")
    print("Waiting messages from broker...")

    # Sleep forever
    while (True):
        time.sleep(60)

    mqtt_client.close()
import time
import ttn
import json

app_id = "<your TTN application id>"
access_key = "<your TTN application access key>"


def uplink_callback(msg, client):
    print('wind_analog: ', msg.payload_fields.analog_in_5)
    print('temp: ', msg.payload_fields.temperature_1)
    print('press: ', msg.payload_fields.barometric_pressure_3)
    print('humid: ', msg.payload_fields.relative_humidity_2)


handler = ttn.HandlerClient(app_id, access_key)

# using mqtt client
mqtt_client = handler.data()
mqtt_client.set_uplink_callback(uplink_callback)

while True:
    mqtt_client.connect()
    time.sleep(60)
# mqtt_client.close()

# using application manager client
app_client = handler.application()
my_app = app_client.get()
# print(my_app)
my_devices = app_client.devices()