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() )
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
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
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
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) try: latitude, _, longitude, _ = gpsBricklet.get_coordinates() altitude = gpsBricklet.get_altitude() temperature = tempBricklet.get_temperature() air_pressure = barometerBricklet.get_air_pressure() sendMessage(client, air_pressure,temperature,longitude,latitude,altitude) except e: print(e)
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() temp=tempBrick.get_temperature()/100 tempString="%.2f" % temp #Sends and reads the data in an infinite loop. while True: #Check if the sampletime has passed and we have to send new data if time.time()-startTime>controller1.sampleTime/1000: #Read the temperature. temp=tempBrick.get_temperature()/100 #Save this for the log-file tempString="%.2f" % temp #Send the temperature buffer1=controller1.getBuffer() buffer2=controller2.getBuffer() fileToWrite.write("\nPi buffer for controller1: "+str(datetime.now())[:19]+","+str(buffer1)+"\n") fileToWrite.write("Pi buffer for controller2: "+str(datetime.now())[:19]+","+str(buffer2)+"\n\n")
#!/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()
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())
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
class TempReader(): def __init__(self, ipcon): self.dev = BrickletTemperature(UID, ipcon) def get(self): return self.dev.get_temperature() / 100.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()