Пример #1
0
def print_temperature(conn, settings, uid):
    from tinkerforge.bricklet_temperature import BrickletTemperature

    br = BrickletTemperature(uid, conn)
    print_generic(
        settings, "temperature", br.get_identity(), 0.01, "\N{DEGREE SIGN}C", br.get_temperature()
    )
Пример #2
0
 def get_temperature(self):
     try:
         t = BrickletTemperature(self.TEMP_UID, self.ipcon)
         self.ipcon.connect(self.HOST, self.PORT)
         temperature = t.get_temperature()
         self.ipcon.disconnect()
         return float(temperature / 100.0)
     except:
         return None
Пример #3
0
def lies_temp(host, port, uid):
	temp = None
	
	try:
		ipcon = IPConnection()
		b = BrickletTemperature(uid, ipcon)
		ipcon.connect(host, port)
	
		temp = b.get_temperature() / 100.0
		
		ipcon.disconnect()
	except:
		print("Temperaturabfrage fehlgeschlagen")
		
	return temp
Пример #4
0
def connect_sensors(sensors, uids, ipcon):
    """
	Creates Bricklet Instances
	:param sensors: connected sensors, as dictionary
	:param uids: bricklets uids, as dictionary
	:param ipcon: ipconnection from tinkerforge
	:return: Dictionary with all instances from connected sensors
	"""
    # Dictionary with all connected sensors
    con_sensors = {}
    for sensor in sensors:
        if sensor == "ambient_light":
            al = BrickletAmbientLightV2(uids["ambient_light"], ipcon)
            con_sensors.update({"ambient_light": al})
        if sensor == "barometer":
            barometer = BrickletBarometer(uids["barometer"], ipcon)
            con_sensors.update({"barometer": barometer})
        if sensor == "humidity":
            humidity = BrickletHumidity(uids["humidity"], ipcon)
            con_sensors.update({"humidity": humidity})
        if sensor == "lcd":
            lcd = BrickletLCD20x4(uids["lcd"], ipcon)
            con_sensors.update({"lcd": lcd})
        if sensor == "moisture":
            moisture = BrickletMoisture(uids["moisture"], ipcon)
            con_sensors.update({"moisture": moisture})
        if sensor == "temperature":
            temperature = BrickletTemperature(uids["temperature"], ipcon)
            con_sensors.update({"temperature": temperature})
        if sensor == "thermocouple":
            thermo = BrickletThermocouple(uids["thermocouple"], ipcon)
            con_sensors.update({"thermocouple": thermo})
    return con_sensors
Пример #5
0
 def begin(self, *args, **keywordParameters):
     #Start the connection with the Tinkerforge sensor
     if "sensorUID" in keywordParameters and "sensor_type" in keywordParameters:
         self.uid = keywordParameters["sensorUID"]
         self.sensor_type = keywordParameters["sensor_type"]
         self.ipcon = IPConnection()
         if self.sensor_type == "temperature":
             self.bricklet = BrickletTemperature(self.uid, self.ipcon)
         elif self.sensor_type == "temperatureV2":
             self.bricklet = BrickletTemperatureV2(self.uid, self.ipcon)
         elif self.sensor_type == "humidity":
             self.bricklet = BrickletHumidityV2(self.uid, self.ipcon)
         else:
             print(
                 "No specific Bricklet passed, defaulting to Temperature Bricklet."
             )
             self.bricklet = BrickletTemperature(self.uid, self.ipcon)
         self.ipcon.connect(self.host, self.port)
Пример #6
0
def lies_temp(host, port, uid):
    temp = None

    try:
        ipcon = IPConnection()
        b = BrickletTemperature(uid, ipcon)
        ipcon.connect(host, port)

        tt = 0.0

        for i in range(10):
            tt = tt + b.get_temperature()

        ipcon.disconnect()
    except:
        print("Temperaturabfrage fehlgeschlagen")

    temp = tt / 1000.0

    return temp
Пример #7
0
def connect_sensors():
    global al
    global barometer
    global humidity
    global lcd
    global moisture
    global temperature
    global thermo

    if sensors["ambient_light"] == 1:
        al = BrickletAmbientLightV2(UID_AMBIENT, ipcon)
    if sensors["barometer"] == 1:
        barometer = BrickletBarometer(UID_BAROMETER, ipcon)
    if sensors["humidity"] == 1:
        humidity = BrickletHumidity(UID_HUMIDITY, ipcon)
    if sensors["lcd"] == 1:
        lcd = BrickletLCD20x4(UID_LCD, ipcon)
    if sensors["moisture"] == 1:
        moisture = BrickletMoisture(UID_MOISTURE, ipcon)
    if sensors["temperature"] == 1:
        temperature = BrickletTemperature(UID_TEMPERATURE, ipcon)
    if sensors["thermo_couple"] == 1:
        thermo = BrickletThermocouple(UID_THERMO, ipcon)
Пример #8
0
# Import
from time import sleep

# Tinkerforge
from tinkerforge.ip_connection import IPConnection
from tinkerforge.bricklet_temperature import BrickletTemperature
from tinkerforge.bricklet_barometer import BrickletBarometer
from tinkerforge.bricklet_humidity_v2 import BrickletHumidityV2
from tinkerforge.bricklet_ambient_light_v2 import AmbientLightV2
from tinkerforge.bricklet_sound_pressure_level import BrickletSoundPressureLevel
from tinkerforge.bricklet_motorized_linear_poti import BrickletMotorizedLinearPoti

# Sensors
ipcon = IPConnection()  # Create IP connection
temp = BrickletTemperature(UIDt, ipcon)  # Create device object
baro = BrickletBarometer(UIDb, ipcon)
humi = BrickletHumidityV2(UIDh, ipcon)
ambi = AmbientLightV2(UIDa, ipcon)
spl = BrickletSoundPressureLevel(UIDs, ipcon)
mlp = BrickletMotorizedLinearPoti(UIDm, ipcon)

ipcon.connect(HOST, PORT)  # Connect to brickd
# Don't use device before ipcon is connected


def getBrickletTemperature():
    return temp.get_temperature()


def getBrickletBarometer():
Пример #9
0
def main():
    global tfIDs
    mqttc = mqtt.Client("")
    mqttc.username_pw_set(USERNAME, password=PASSWORD)
    mqttc.tls_set(ca_certs="{}/fakelerootx1.pem".format(os.getcwd()),
                  certfile=None,
                  keyfile=None,
                  cert_reqs=ssl.CERT_REQUIRED,
                  tls_version=ssl.PROTOCOL_TLS,
                  ciphers=None)
    mqttc.connect(MQTT_ADAPTER_IP,
                  MQTT_ADAPTER_PORT)  # mqtt.abc.re.je == 35.242.131.248:30883
    mqttc.loop_start()

    if TF_CONNECT:
        # Create connection and connect to brickd
        ipcon = IPConnection()

        TPS1_bricklet = BrickletTemperature(TPS1_UID, ipcon)
        HMS1_bricklet = BrickletHumidity(HMS1_UID, ipcon)
        LPS1_bricklet = BrickletAmbientLightV2(LPS1_UID, ipcon)

        ipcon.connect(TF_HOST, TF_PORT)

        # Register Enumerate Callback
        ipcon.register_callback(IPConnection.CALLBACK_ENUMERATE, cb_enumerate)

        # Trigger Enumerate
        ipcon.enumerate()

        time.sleep(2)

    if DEBUG:
        print(tfIDs)

    if PUBLISH:

        # Get current temperature
        TPS1 = TPS1_bricklet.get_temperature() / 100.0
        HMS1 = HMS1_bricklet.get_humidity() / 10.0
        LPS1 = LPS1_bricklet.get_illuminance() / 100.0

        today = dt.now().strftime("%Y-%m-%d %H:%M")
        today_0 = dt.now().strftime("%Y-%m-%d 00:00")
        t = dt.now().strftime("%H:%M")
        # dtt = dateutil.parser.parse(today)
        dtt = dt.utcnow()

        points_TPS1 = {}
        points_TPS1["temperature"] = {"present_value": TPS1}

        points_HMS1 = {}
        points_HMS1["humidity"] = {"present_value": HMS1}

        points_LPS1 = {}
        points_LPS1["illuminance"] = {"present_value": LPS1}

        udmi_payload_TPS1 = str(udmi.Pointset(dtt, points_TPS1))
        # print(udmi_payload_TPS1)
        udmi_payload_HMS1 = str(udmi.Pointset(dtt, points_HMS1))
        # print(udmi_payload_HMS1)
        udmi_payload_LPS1 = str(udmi.Pointset(dtt, points_LPS1))
        # print(udmi_payload_LPS1)

        payload_norm_TPS1 = json_normalize(
            json.loads(udmi_payload_TPS1)).to_json(
                orient='records').strip('[]')
        print(payload_norm_TPS1)
        payload_norm_HMS1 = json_normalize(
            json.loads(udmi_payload_HMS1)).to_json(
                orient='records').strip('[]')
        print(payload_norm_HMS1)
        payload_norm_LPS1 = json_normalize(
            json.loads(udmi_payload_LPS1)).to_json(
                orient='records').strip('[]')
        print(payload_norm_LPS1)

        # msg = json.dumps({"wind": wind, "humidity": humidity, "temperature": temperature})

        # infot = mqttc.publish("telemetry", udmi_payload, qos=1)
        # print("Sending {}".format(udmi_payload_TPS1))
        infot = mqttc.publish("telemetry/myapp.iot/{}".format("TPS-1"),
                              payload_norm_TPS1,
                              qos=1)
        # print("Sending {}".format(udmi_payload_HMS1))
        infot = mqttc.publish("telemetry/myapp.iot/{}".format("HMS-1"),
                              payload_norm_HMS1,
                              qos=1)
        # print("Sending {}".format(udmi_payload_LPS1))
        infot = mqttc.publish("telemetry/myapp.iot/{}".format("LPS-1"),
                              payload_norm_LPS1,
                              qos=1)

        infot.wait_for_publish()
#Print the settings in the log file.
fileToWrite=open("/home/pi/Documents/PID_controller/lab_temperature_data/twocontrollerData_"+(str(datetime.now())[:19]).replace(" ", "_")+".txt",'w')

fileToWrite.write("The first coloumn of data is the time, the second is the  temperature and the last is the  output of the controller.\n\n")
fileToWrite.write("The settings of the first controller are:\n"+"kp: "+str(controller1.getKp())+", ki: "+str(controller1.getKi())+", kd: "+str(controller1.getKd())+", setpoint: "+str(controller1.getSetpoint())+" ,sample time: "+str(controller1.getSampleTime())+" ms"+"\n\n")
fileToWrite.write("The settings of the second controller are:\n"+"kp: "+str(controller2.getKp())+", ki: "+str(controller2.getKi())+", kd: "+str(controller2.getKd())+", setpoint: "+str(controller2.getSetpoint())+" ,sample time: "+str(controller2.getSampleTime())+" ms"+"\n\n")

if __name__ == "__main__":

		#Build a connection to the bricklet.
		HOST="localhost"
		PORT=4223
		UID="zHk"

		ipcon = IPConnection()
		tempBrick = BrickletTemperature(UID,ipcon)
		ipcon.connect(HOST,PORT)

		data=b''

		time.sleep(1)

		#Save the at which we started, so that we know when to send new data.
		startTime=time.time()

		#change the mode to automatic, so that both controllers start at zero.
		controller1.changeMode(1)
		controller2.changeMode(1)
		controller1.sendNewValues()
		controller2.sendNewValues()
Пример #11
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-

HOST = "localhost"
PORT = 4223
UID = "XYZ"  # Change XYZ to the UID of your Temperature Bricklet

from tinkerforge.ip_connection import IPConnection
from tinkerforge.bricklet_temperature import BrickletTemperature

if __name__ == "__main__":
    ipcon = IPConnection()  # Create IP connection
    t = BrickletTemperature(UID, ipcon)  # Create device object

    ipcon.connect(HOST, PORT)  # Connect to brickd
    # Don't use device before ipcon is connected

    # Get current temperature (unit is °C/100)
    temperature = t.get_temperature()
    print("Temperature: " + str(temperature / 100.0) + " °C")

    raw_input("Press key to exit\n")  # Use input() in Python 3
    ipcon.disconnect()
Пример #12
0
 def create_instance(self, uid, ipcon):
     return BrickletTemperature(uid, ipcon)
Пример #13
0
def print_temperature(conn, settings, uid):
    from tinkerforge.bricklet_temperature import BrickletTemperature  # type: ignore[import] # pylint: disable=import-error,import-outside-toplevel
    br = BrickletTemperature(uid, conn)
    print_generic(settings, "temperature", br.get_identity(), 0.01, u"\N{DEGREE SIGN}C",
                  br.get_temperature())
Пример #14
0
# -*- coding: utf-8 -*-

HOST = "localhost"
PORT = 4223
UID = "XYZ" # Change XYZ to the UID of your Temperature Bricklet

from tinkerforge.ip_connection import IPConnection
from tinkerforge.bricklet_temperature import BrickletTemperature

# Callback function for temperature callback (parameter has unit °C/100)
def cb_temperature(temperature):
    print("Temperature: " + str(temperature/100.0) + " °C")

if __name__ == "__main__":
    ipcon = IPConnection() # Create IP connection
    t = BrickletTemperature(UID, ipcon) # Create device object

    ipcon.connect(HOST, PORT) # Connect to brickd
    # Don't use device before ipcon is connected

    # Register temperature callback to function cb_temperature
    t.register_callback(t.CALLBACK_TEMPERATURE, cb_temperature)

    # Set period for temperature callback to 1s (1000ms)
    # Note: The temperature callback is only called every second
    #       if the temperature has changed since the last call!
    t.set_temperature_callback_period(1000)

    raw_input("Press key to exit\n") # Use input() in Python 3
    ipcon.disconnect()
Пример #15
0
PORT = 4223
UID = "XYZ"  # Change XYZ to the UID of your Temperature Bricklet

from tinkerforge.ip_connection import IPConnection
from tinkerforge.bricklet_temperature import BrickletTemperature


# Callback function for temperature reached callback (parameter has unit °C/100)
def cb_temperature_reached(temperature):
    print("Temperature: " + str(temperature / 100.0) + " °C")
    print("It is too hot, we need air conditioning!")


if __name__ == "__main__":
    ipcon = IPConnection()  # Create IP connection
    t = BrickletTemperature(UID, ipcon)  # Create device object

    ipcon.connect(HOST, PORT)  # Connect to brickd
    # Don't use device before ipcon is connected

    # Get threshold callbacks with a debounce time of 10 seconds (10000ms)
    t.set_debounce_period(10000)

    # Register temperature reached callback to function cb_temperature_reached
    t.register_callback(t.CALLBACK_TEMPERATURE_REACHED, cb_temperature_reached)

    # Configure threshold for temperature "greater than 30 °C" (unit is °C/100)
    t.set_temperature_callback_threshold(">", 30 * 100, 0)

    raw_input("Press key to exit\n")  # Use input() in Python 3
    ipcon.disconnect()
HOST = "localhost"
PORT = 4223
UID = "XYZ" # Change XYZ to the UID of your Temperature Bricklet

from tinkerforge.ip_connection import IPConnection
from tinkerforge.bricklet_temperature import BrickletTemperature

# Callback function for temperature reached callback
def cb_temperature_reached(temperature):
    print("Temperature: " + str(temperature/100.0) + " °C")
    print("It is too hot, we need air conditioning!")

if __name__ == "__main__":
    ipcon = IPConnection() # Create IP connection
    t = BrickletTemperature(UID, ipcon) # Create device object

    ipcon.connect(HOST, PORT) # Connect to brickd
    # Don't use device before ipcon is connected

    # Get threshold callbacks with a debounce time of 10 seconds (10000ms)
    t.set_debounce_period(10000)

    # Register temperature reached callback to function cb_temperature_reached
    t.register_callback(t.CALLBACK_TEMPERATURE_REACHED, cb_temperature_reached)

    # Configure threshold for temperature "greater than 30 °C"
    t.set_temperature_callback_threshold(">", 30*100, 0)

    raw_input("Press key to exit\n") # Use input() in Python 3
    ipcon.disconnect()
Пример #17
0
class TempReader():
    def __init__(self, ipcon):
        self.dev = BrickletTemperature(UID, ipcon)

    def get(self):
        return self.dev.get_temperature() / 100.0
Пример #18
0
class PIDSender:
    @property
    def sequence_number(self):
        self.__sequence_number = (self.__sequence_number % 15) + 1
        return self.__sequence_number

    def __init__(self, sensor_ip='localhost', sensor_port=4223):
        #Stuff that is needed to build a connection with the temperature bricklet.
        self.host = sensor_ip
        self.port = sensor_port
        self.uid = 0
        self.ipcon = 0
        self.bricklet = 0
        self.sensor_type = "temperature"

        #The data that will be send is saved in this dict.
        self.dataToSend = {}

        #Initale values of the PID controller.
        self.kp = 0.0
        self.ki = 0.0
        self.kd = 0.0
        self.lowerOutputLimit = 0.0
        self.upperOutputLimit = 4095
        self.mode = 1
        self.sampleTime = 1000
        self.direction = True
        self.setpoint = 22.50
        self.output = -1.0
        self.__sequence_number = 0

        #Floating point numbers send as integers using fixed point arithmetic.
        self.fixedPoint = 16

    #Before a communciation can be established the begin()-method has to be called.
    #It takes an optional parameter which is the UID of the Tinkerforge temperature sensor (e.g. "zih").
    #Type is the type of the sensor
    def begin(self, *args, **keywordParameters):
        #Start the connection with the Tinkerforge sensor
        if "sensorUID" in keywordParameters and "sensor_type" in keywordParameters:
            self.uid = keywordParameters["sensorUID"]
            self.sensor_type = keywordParameters["sensor_type"]
            self.ipcon = IPConnection()
            if self.sensor_type == "temperature":
                self.bricklet = BrickletTemperature(self.uid, self.ipcon)
            elif self.sensor_type == "temperatureV2":
                self.bricklet = BrickletTemperatureV2(self.uid, self.ipcon)
            elif self.sensor_type == "humidity":
                self.bricklet = BrickletHumidityV2(self.uid, self.ipcon)
            else:
                print(
                    "No specific Bricklet passed, defaulting to Temperature Bricklet."
                )
                self.bricklet = BrickletTemperature(self.uid, self.ipcon)
            self.ipcon.connect(self.host, self.port)

    def set_gain(self, value):
        self.dataToSend[constants.MessageType.set_gain] = bool(value)

    def set_kp(self, value):
        self.dataToSend[constants.MessageType.set_kp] = value

    def set_ki(self, value):
        self.dataToSend[constants.MessageType.set_ki] = value

    def set_kd(self, value):
        self.dataToSend[constants.MessageType.set_kd] = value

    def set_pid_enable(self, value):
        self.dataToSend[constants.MessageType.set_enable] = value

    def set_output_limit_low(self, value):
        self.dataToSend[constants.MessageType.set_lower_output_limit] = value

    def set_output_limit_high(self, value):
        self.dataToSend[constants.MessageType.set_upper_output_limit] = value

    def set_timeout(self, value):
        self.dataToSend[constants.MessageType.set_timeout] = value

    def set_pid_direction(self, value):
        self.dataToSend[constants.MessageType.set_direction] = value

    def set_setpoint(self, value):
        self.dataToSend[constants.MessageType.set_setpoint] = value

    def set_output(self, value):
        self.dataToSend[constants.MessageType.set_output] = value

    def encodeWithCobs(self, data):
        return bytearray(cobs.encode(data) + b'\x00')

    #Takes a number that was converted with fixed point arithmetic as input and returns the original number.
    def fixedPointIntToFloat(self, intToConvert):
        return (intToConvert / 2**(self.fixedPoint))

    """
    All the getter methods.
    """

    def getKp(self):
        return self.kp

    def getKd(self):
        return self.kd

    def getKi(self):
        return self.ki

    def getLowerOutputLimit(self):
        return self.lowerOutputLimit

    def getUpperOutputLimit(self):
        return self.upperOutputLimit

    def getMode(self):
        return self.mode

    def getDirection(self):
        return self.direction

    def getSetpoint(self):
        return self.setpoint

    def getOutput(self):
        return self.output

    def getFixedPoint(self):
        return self.fixedPoint

    def getBaudRate(self):
        return self.baudRate

    def getTemperature(self):
        # The temperature range is -40 °C - 125 °C
        # We will convert this range to a uin32_t
        # hence (temp + 40) / 165
        return int((self.bricklet.get_temperature() / 100 + 40) / 165 * 2**16)

    def getBuffer(self):
        return self.dataToSend
Пример #19
0
    def cb_enumerate(cls, uid, connected_uid, position, hardware_version,
                     firmware_version, device_identifier, enumeration_type):
        #global self.led
        found = False
        if enumeration_type == IPConnection.ENUMERATION_TYPE_CONNECTED or \
           enumeration_type == IPConnection.ENUMERATION_TYPE_AVAILABLE:
            # Enumeration for LED
            if device_identifier == LEDStrip.DEVICE_IDENTIFIER:
                cls.LEDs.append(LEDStrip(uid, cls.ipcon))
                temp_uid = str(cls.LEDs[-1].get_identity()[1]) + "." + str(
                    cls.LEDs[-1].get_identity()[0])
                cls.LEDList.addLED(cls.LEDs[-1], temp_uid)
                cls.LEDs[-1].set_frame_duration(200)
                if settings.LEDs.get(temp_uid) <> None:
                    cls.LEDs[-1].set_chip_type(settings.LEDs.get(temp_uid)[0])
                    cls.LEDs[-1].set_frame_duration(
                        settings.LEDs.get(temp_uid)[1])
                    found = True
                #self.led.register_callback(self.led.CALLBACK_FRAME_RENDERED,
                #                lambda x: __cb_frame_rendered__(self.led, x))
                #self.led.set_rgb_values(0, self.NUM_LEDS, self.r, self.g, self.b)
                #self.led.set_rgb_values(15, self.NUM_LEDS, self.r, self.g, self.b)
                #self.led.set_rgb_values(30, self.NUM_LEDS, self.r, self.g, self.b)

            if device_identifier == IO16.DEVICE_IDENTIFIER:
                cls.io.append(IO16(uid, cls.ipcon))
                temp_uid = str(cls.io[-1].get_identity()[1]) + "." + str(
                    cls.io[-1].get_identity()[0])
                cls.io16list.addIO(cls.io[-1], temp_uid, 16)
                cls.io[-1].set_debounce_period(100)
                if settings.IO16.get(temp_uid) <> None:
                    cls.io[-1].set_port_interrupt(
                        'a',
                        settings.IO16.get(temp_uid)[0])
                    cls.io[-1].set_port_interrupt(
                        'b',
                        settings.IO16.get(temp_uid)[1])
                    cls.io[-1].set_port_configuration(
                        'a',
                        settings.IO16.get(temp_uid)[0], 'i', True)
                    cls.io[-1].set_port_configuration(
                        'b',
                        settings.IO16.get(temp_uid)[1], 'i', True)
                    cls.io[-1].set_port_configuration(
                        'a',
                        settings.IO16.get(temp_uid)[2], 'o', False)
                    cls.io[-1].set_port_configuration(
                        'b',
                        settings.IO16.get(temp_uid)[3], 'o', False)
                    #self.io[-1].set_port_monoflop('a', tifo_config.IO16.get(temp_uid)[4],0,tifo_config.IO16.get(temp_uid)[6])
                    #self.io[-1].set_port_monoflop('b', tifo_config.IO16.get(temp_uid)[5],0,tifo_config.IO16.get(temp_uid)[6])
                    cls.io[-1].register_callback(
                        cls.io[-1].CALLBACK_INTERRUPT,
                        partial(cls.cb_interrupt,
                                device=cls.io[-1],
                                uid=temp_uid))
                    found = True

            if device_identifier == AmbientLight.DEVICE_IDENTIFIER:
                cls.al.append(AmbientLight(uid, cls.ipcon))
                cls.al[-1].set_illuminance_callback_threshold('o', 0, 0)
                cls.al[-1].set_debounce_period(10)
                #self.al.set_illuminance_callback_threshold('<', 30, 30)
                #self.al.set_analog_value_callback_period(10000)
                #self.al.set_illuminance_callback_period(10000)
                #self.al.register_callback(self.al.CALLBACK_ILLUMINANCE, self.cb_ambLight)
                #self.al.register_callback(self.al.CALLBACK_ILLUMINANCE_REACHED, self.cb_ambLight)
                args = cls.al[-1]
                #self.al[-1].register_callback(self.al[-1].CALLBACK_ILLUMINANCE_REACHED, lambda event1, event2, event3, args=args: self.cb_ambLight(event1, event2, event3, args))

                cls.al[-1].register_callback(
                    cls.al[-1].CALLBACK_ILLUMINANCE_REACHED,
                    partial(cls.cb_ambLight, device=args))
                temp_uid = str(cls.al[-1].get_identity()[1]) + "." + str(
                    cls.al[-1].get_identity()[0])

                thread_cb_amb = Timer(60, cls.thread_ambLight, [cls.al[-1]])
                thread_cb_amb.start()

            if device_identifier == BrickletCO2.DEVICE_IDENTIFIER:
                cls.co2.append(BrickletCO2(uid, cls.ipcon))
                temp_uid = str(cls.co2[-1].get_identity()[1]) + "." + str(
                    cls.co2[-1].get_identity()[0])
                thread_co2_ = Timer(5, cls.thread_CO2, [cls.co2[-1]])
                thread_co2_.start()
                cls.threadliste.append(thread_co2_)

            if device_identifier == BrickletDualRelay.DEVICE_IDENTIFIER:
                cls.drb.append(BrickletDualRelay(uid, cls.ipcon))


#
#            if device_identifier == Moisture.DEVICE_IDENTIFIER:
#                self.moist = Moisture(uid, self.ipcon)
#                self.moist.set_moisture_callback_period(10000)
#                self.moist.register_callback(self.moist.CALLBACK_MOISTURE, self.cb_moisture)

            if device_identifier == BrickletMotionDetector.DEVICE_IDENTIFIER:
                cls.md.append(BrickletMotionDetector(uid, cls.ipcon))
                temp_uid = str(cls.md[-1].get_identity()[1]) + "." + str(
                    cls.md[-1].get_identity()[0])
                cls.md[-1].register_callback(
                    cls.md[-1].CALLBACK_MOTION_DETECTED,
                    partial(cls.cb_md, device=cls.md[-1], uid=temp_uid))
                cls.md[-1].register_callback(
                    cls.md[-1].CALLBACK_DETECTION_CYCLE_ENDED,
                    partial(cls.cb_md_end, device=cls.md[-1], uid=temp_uid))

            if device_identifier == BrickletSoundIntensity.DEVICE_IDENTIFIER:
                cls.si.append(BrickletSoundIntensity(uid, cls.ipcon))
                temp_uid = str(cls.si[-1].get_identity()[1]) + "." + str(
                    cls.si[-1].get_identity()[0])

                cls.si[-1].set_debounce_period(1000)
                cls.si[-1].register_callback(
                    cls.si[-1].CALLBACK_INTENSITY_REACHED,
                    partial(cls.cb_si, device=cls.si[-1], uid=temp_uid))
                cls.si[-1].set_intensity_callback_threshold('>', 200, 0)

            if device_identifier == BrickletPTC.DEVICE_IDENTIFIER:
                cls.ptc.append(BrickletPTC(uid, cls.ipcon))
                temp_uid = str(cls.ptc[-1].get_identity()[1]) + "." + str(
                    cls.ptc[-1].get_identity()[0])
                thread_pt_ = Timer(5, cls.thread_pt, [cls.ptc[-1]])
                thread_pt_.start()
                cls.threadliste.append(thread_pt_)

            if device_identifier == BrickletTemperature.DEVICE_IDENTIFIER:
                cls.temp.append(BrickletTemperature(uid, cls.ipcon))
                temp_uid = str(cls.temp[-1].get_identity()[1]) + "." + str(
                    cls.temp[-1].get_identity()[0])
                thread_pt_ = Timer(5, cls.thread_pt, [cls.temp[-1]])
                thread_pt_.start()
                cls.threadliste.append(thread_pt_)

            if device_identifier == BrickMaster.DEVICE_IDENTIFIER:
                cls.master.append(BrickMaster(uid, cls.ipcon))
                thread_rs_error = Timer(60, cls.thread_RSerror, [])
                #thread_rs_error.start()
                if settings.inputs.get(uid) <> None:
                    found = True

            if not found:
                toolbox.log(connected_uid, uid, device_identifier)
                print connected_uid, uid, device_identifier
Пример #20
0
def on_disconnect(client, userdata, rc):
    print("Disconnected, exiting")
    sys.exit(1)

def sendMessage(client, pressure, temperature, longitude, latitude, altitude):
    # timestamp; pressure; temprature; longitude, latitude, altitude
    payload = "{};{};{};{};{};{}".format(time.time(), pressure, temperature, longitude, latitude, altitude.altitude)
    topic = "collectors/{}/metrics".format(client_id)
    success = client.publish(topic, payload, qos=0, retain=False)
    print("{}: {}".format(topic, payload))

if __name__ == "__main__":
    # Tinkerforge setup
    ipcon = IPConnection() 
    tempBricklet = BrickletTemperature(TEMPUID, ipcon)
    barometerBricklet = BrickletBarometer(BARUID, ipcon)
    gpsBricklet = BrickletGPSV2(GPSUID, ipcon) 
    ipcon.connect(HOST, PORT) 

    # MQTT Setup
    client = mqtt.Client(client_id=client_id)
    client.on_connect = on_connect
    client.on_disconnect = on_disconnect
    client.tls_set("dapo.pem")
    client.username_pw_set("rpi", "p00rT7daH7Lnb0HzMfA0d+zY2fAOo3")
    client.connect("dapo.0x80.ch", 8883, 30)

    # Send loop
    while(True):
        time.sleep(5)
Пример #21
0
'''
Maybe use following guide to make this an mqtt client?
https://www.hivemq.com/blog/mqtt-client-library-paho-python
'''

from tinkerforge.ip_connection import IPConnection
from tinkerforge.bricklet_temperature import BrickletTemperature
import time

#HOST = "192.168.63.183"  # hopefully we can keep this ip for a while...
HOST = ''
PORT = 4223  # port can be switched via brickviewer configuration tab
UID = "e2q"  # uid of the temperature bricklet. see brick viewer for other uids

if __name__ == "__main__":
    ipcon = IPConnection()
    t = BrickletTemperature(UID, ipcon)

    ipcon.connect(HOST, PORT)

    try:
        while True:
            temperature = t.get_temperature()
            print("Temperature: " + str(temperature/100.0) + " °C")
            time.sleep(1)
    except KeyboardInterrupt:
        print('\nChecking temperature end.')

    ipcon.disconnect()
Пример #22
0
 def initSensor(self):
     s = BrickletTemperature(self.uid, self.ipconnection)
     self.ipconnection.connect(self.host, self.port)
     return s
Пример #23
0
 def __init__(self, ipcon):
     self.dev = BrickletTemperature(UID, ipcon)