def temperature(connection, table):
    ipcon = IPConnection()
    t = Temperature(TEMPERATURE_UID, ipcon)
    ipcon.connect(HOST, PORT)
    value = t.get_temperature() / 100.0
    insert(connection, table, time.time(), value)
    ipcon.disconnect()
def humidity(connection, table):
    ipcon = IPConnection()
    h = Humidity(HUMIDITY_UID, ipcon)
    ipcon.connect(HOST, PORT)
    value = h.get_humidity() / 10.0
    insert(connection, table, time.time(), value)
    ipcon.disconnect()
Exemple #3
0
class PressureSensor():
    def __init__(self, uid, host):

        self._host = host
        self._port = 4223
        self._uid = uid  # Change XYZ to the UID of your Load Cell Bricklet 2.0

        self._connect()

    def _connect(self):
        print(self._host)
        print(self._port)
        print(self._uid)

        self._ipcon = IPConnection()  # Create IP connection
        self._lc = BrickletLoadCellV2(self._uid,
                                      self._ipcon)  # Create device object

        self._ipcon.connect(self._host, self._port)  # Connect to brickd

    def disconnect(self):

        self._ipcon.disconnect()

    def get(self):
        return self._lc.get_weight()
def ambient(connection, table):
    ipcon = IPConnection()
    al = AmbientLight(AMBIENT_UID, ipcon)
    ipcon.connect(HOST, PORT)
    value = al.get_illuminance() / 10.0  # Get current illuminance (unit is Lux/10)
    insert(connection, table, time.time(), value)
    ipcon.disconnect()
def SetBrickletRGB(self, r, g, b):
    Domoticz.Debug("SetBrickletRGB: R=%d,G=%d,B=%d" % (r, g, b))
    try:
        # Create IP connection
        ipConn = IPConnection()
        # Create device object
        rgbDev = BrickletRGBLEDV2(Parameters["Mode1"], ipConn)
        # Connect to brickd using Host and Port
        ipConn.connect(Parameters["Address"], int(Parameters["Port"]))
        # Assign the color and update the domoticz dimmer switches
        state = 1
        self.r = r
        Devices[UNITCHANNELR].Update(nValue=state, sValue=str(self.r))
        self.g = g
        Devices[UNITCHANNELG].Update(nValue=state, sValue=str(self.g))
        self.b = b
        Devices[UNITCHANNELB].Update(nValue=state, sValue=str(self.b))
        # Update the tinkerforge rgbled device with mapped values
        rm = MapRange(self.r, 0, 100, 0, 255)
        gm = MapRange(self.g, 0, 100, 0, 255)
        bm = MapRange(self.b, 0, 100, 0, 255)
        Domoticz.Debug("Bricklet Update: R=%d,G=%d,B=%d" % (rm, gm, bm))
        rgbDev.set_rgb_value(rm, gm, bm)
        # Disconnect
        ipConn.disconnect()
        Domoticz.Debug("SetBrickletRGB: OK")
    except:
        Domoticz.Error("[ERROR] SetBrickletRGB failed. Check bricklet.")
    return
def SetLCDText(self, line1, line2, line3, line4):
    Domoticz.Debug("SetLCDText - UID:" + self.UIDList[UIDINDEXLCD])
    try:
        # Create IP connection
        ipcon = IPConnection()
        # Create device object
        lcd = BrickletLCD20x4(self.UIDList[UIDINDEXLCD], ipcon)
        # Connect to brickd
        ipcon.connect(Parameters["Address"], int(Parameters["Port"]))
        # Don't use device before ipcon is connected
        ## write to the lcd: line (int,0-3),pos(int,0-19),text
        lcd.clear_display()
        lcd.write_line(0, 0, line1)
        lcd.write_line(1, 0, line2)
        lcd.write_line(2, 0, line3)
        lcd.write_line(3, 0, line4)

        ipcon.disconnect()

        return 1

    except:
        # Error
        Domoticz.Log("[ERROR] Can not set Master Status LED.")
        return 0
def SetAirQualityStatusLed(self, state):
    Domoticz.Debug("SetAirQualityStatusLed - UID:" +
                   self.UIDList[UIDINDEXAIRQUALITY])
    try:
        # Create IP connection
        ipcon = IPConnection()
        # Create device object
        aq = BrickletAirQuality(self.UIDList[UIDINDEXAIRQUALITY], ipcon)
        # Connect to brickd
        ipcon.connect(Parameters["Address"], int(Parameters["Port"]))
        # Don't use device before ipcon is connected
        if state == 0:
            aq.set_status_led_config(state)
            Domoticz.Log("Air Quality Status LED disabled.")

        if state == 1:
            aq.set_status_led_config(state)
            Domoticz.Log("Air Quality Status LED enabled.")

        ipcon.disconnect()

        return 1

    except:
        # Error
        Domoticz.Log("[ERROR] Can not set Air Quality Status LED.")
        return 0
Exemple #8
0
def start_app():

    # Create Tinkerforge instances
    ip_con = IPConnection()
    ip_con.set_timeout(10)
    ip_con.connect('localhost', 4223)
    controller.BrickletHandler.monitor_ip_connection(ip_con=ip_con)

    bricklet_factory = controller.BrickletFactory()
    quad_relay_1 = bricklet_factory. \
        create_and_configure_bricklet('quad_relay', 'BC8', ip_con)
    quad_relay_2 = bricklet_factory. \
        create_and_configure_bricklet('quad_relay', 'BCE', ip_con)
    rs232 = bricklet_factory. \
        create_and_configure_bricklet('rs232', 'Cvu', ip_con)
    analog_in = bricklet_factory. \
        create_and_configure_bricklet('analog_in', 'CNA', ip_con)

    # controller Setup
    channel = controller.ChannelController(quad_relay_1, quad_relay_2)
    co2flow = controller.Co2FlowController(rs232)
    airflow = controller.AirFlowController(analog_in)
    sensor = controller.SensorController(analog_in)
    concentration = controller.ConcentrationController(sensor, airflow, co2flow)
    sequence = controller.SequenceController(concentration, channel)

    # logging
    data_logger = data.DataLogger()
    log_dir = 'log'
    if not os.path.exists(log_dir):
        os.mkdir(log_dir)
    prefix = time.strftime('%y%m%d_%H%M%S')

    data_file_path = os.path.join(log_dir, f'{prefix}_data.csv')
    log_file_path = os.path.join(log_dir, f'{prefix}_log.txt')

    logger.set_log_file(log_file_path)
    data_logger.set_file(data_file_path)

    # main components
    main_controller = controller.MainController(
        channel_controller=channel,
        co2_flow_controller=co2flow,
        air_flow_controller=airflow,
        sensor_controller=sensor,
        concentration_controller=concentration,
        sequence_controller=sequence,
        data_logger=data_logger
    )
    gui = tk_gui.MainFrame()
    main_controller.set_gui(gui)

    # Start app
    main_controller.initialize()
    gui.mainloop()

    # Wrap up
    main_controller.set_co2_flow(flow_rate=0)
    main_controller.set_channel(data.Channels.NONE)
    ip_con.disconnect()
def setPins(mcuReset, pcuReset, mcuBoot, pcuBoot):
    ipcon = IPConnection()  # Create IP connection
    relay = BrickletIndustrialQuadRelay(UID_RELAY,
                                        ipcon)  # Create device object

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

    relayValue = 0

    if mcuReset:
        relayValue |= (1 << 0)

    if mcuBoot:
        relayValue |= (1 << 1)

    if pcuReset:
        relayValue |= (1 << 2)

    if pcuBoot:
        relayValue |= (1 << 3)

    relay.set_value(relayValue)

    ipcon.disconnect()
def SetLCDBacklight(self, state):
    Domoticz.Debug("SetLCDBacklight - UID:" + self.UIDList[UIDINDEXLCD])
    try:
        # Create IP connection
        ipcon = IPConnection()
        # Create device object
        lcd = BrickletLCD20x4(self.UIDList[UIDINDEXLCD], ipcon)
        # Connect to brickd
        ipcon.connect(Parameters["Address"], int(Parameters["Port"]))
        # Don't use device before ipcon is connected
        if state == 'Off':
            lcd.backlight_off()
            Domoticz.Log("LCD Backlight OFF.")

        if state == 'On':
            lcd.backlight_on()
            Domoticz.Log("LCD Backlight ON.")

        ipcon.disconnect()

        return 1

    except:
        # Error
        Domoticz.Log("[ERROR] Can not set Master Status LED.")
        return 0
Exemple #11
0
def relay_flash(baudrate, tty, firmware, uid_iqr, uid_master):
    ipcon = IPConnection()
    iqr = BrickletIndustrialQuadRelay(uid_iqr, ipcon)
    master = BrickMaster(uid_master, ipcon)

    ipcon.connect('localhost', 4223)

    #    reset_usb()
    #    time.sleep(1)

    i = 10
    while True:
        if i == 10:
            master.get_chibi_error_log()
            iqr.set_value(MASK_DATA)
            time.sleep(0.2)
            iqr.set_value(MASK_POWER | MASK_DATA)
            i = 0

        i += 1
        try:
            time.sleep(0.01)
            xmc_flash(baudrate, tty, firmware)
            break
        except Exception as e:
            print(str(e))

    iqr.set_value(MASK_POWER)

    master.reset()

    ipcon.disconnect()
Exemple #12
0
class Window(QtGui.QWidget):
    qtcb_temperature = QtCore.pyqtSignal(int)

    def __init__(self):
        QtGui.QWidget.__init__(self)
        self.button = QtGui.QPushButton('Refresh', self)
        self.button.clicked.connect(self.handle_button)
        self.label = QtGui.QLabel('TBD')
        layout = QtGui.QVBoxLayout(self)
        layout.addWidget(self.button)
        layout.addWidget(self.label)

        self.ipcon = IPConnection()
        self.temperature = Temperature(UID_TEMPERATURE, self.ipcon)
        self.ipcon.connect(HOST, PORT)

        # We send the callback through the Qt signal/slot
        # system to make sure that we can change the label
        self.qtcb_temperature.connect(self.cb_temperature)
        self.temperature.register_callback(Temperature.CALLBACK_TEMPERATURE, self.qtcb_temperature.emit)

        # Refresh every second
        self.temperature.set_temperature_callback_period(1000)
        
        # Refresh once on startup
        self.handle_button()

    # Refresh by hand
    def handle_button(self):
        self.cb_temperature(self.temperature.get_temperature())

    def cb_temperature(self, temperature):
        # Show temperature
        self.label.setText(u"Temperature: {0} °C".format(temperature/100.0))
def barometer(connection, table):
    ipcon = IPConnection()
    b = Barometer(BAROMETER_UID, ipcon)
    ipcon.connect(HOST, PORT)
    value = b.get_air_pressure() / 1000.0  # Get current air pressure (unit is mbar/1000)
    insert(connection, table, time.time(), value)
    ipcon.disconnect()
Exemple #14
0
def main(host, port, uid):
    ipcon = IPConnection()
    rs485 = BrickletRS485(uid, ipcon)
    ipcon.connect(host, port)

    #    rs485.set_buffer_config(5*1024, 5*1024)
    print(rs485.get_buffer_status())
Exemple #15
0
def collect_data(suffix):
    global SAMPLE_RATE
    global w1
    global row
    print "Now recording " + suffix

    ipcon = IPConnection() # Create IP connection
    imu = IMU(UID, ipcon) # Create device object

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

    # Set period for quaternion callback to 1s
    imu.set_all_data_period(SAMPLE_RATE)
    imu.set_orientation_period(SAMPLE_RATE)
    imu.set_quaternion_period(SAMPLE_RATE)    
   
    f1 = open('data/letters/all_data_'+suffix+'.csv', 'wb')
    w1 = csv.writer(f1)
    row = []
    # Register quaternion callback
    imu.register_callback(imu.CALLBACK_ALL_DATA, cb_all_data)
    imu.register_callback(imu.CALLBACK_ORIENTATION, cb_orientation_data)
    imu.register_callback(imu.CALLBACK_QUATERNION, cb_quaternion_data)   
  
    
    raw_input('Press key to quit recording ' + suffix + ' \n') # Use input() in Python 3
    ipcon.disconnect()
Exemple #16
0
class Window(QtGui.QWidget):
    qtcb_temperature = QtCore.pyqtSignal(int)

    def __init__(self):
        QtGui.QWidget.__init__(self)
        self.button = QtGui.QPushButton('Refresh', self)
        self.button.clicked.connect(self.handle_button)
        self.label = QtGui.QLabel('TBD')
        layout = QtGui.QVBoxLayout(self)
        layout.addWidget(self.button)
        layout.addWidget(self.label)

        self.ipcon = IPConnection()
        self.temperature = Temperature(UID_TEMPERATURE, self.ipcon)
        self.ipcon.connect(HOST, PORT)

        # We send the callback through the Qt signal/slot
        # system to make sure that we can change the label
        self.qtcb_temperature.connect(self.cb_temperature)
        self.temperature.register_callback(Temperature.CALLBACK_TEMPERATURE,
                                           self.qtcb_temperature.emit)

        # Refresh every second
        self.temperature.set_temperature_callback_period(1000)

        # Refresh once on startup
        self.handle_button()

    # Refresh by hand
    def handle_button(self):
        self.cb_temperature(self.temperature.get_temperature())

    def cb_temperature(self, temperature):
        # Show temperature
        self.label.setText(u"Temperature: {0} °C".format(temperature / 100.0))
def SetMasterStatusLed(self, state):
    Domoticz.Debug("SetMasterStatusLed - UID:" + self.UIDList[UIDINDEXMASTER])
    try:
        # Create IP connection
        ipcon = IPConnection()
        # Create device object
        master = BrickMaster(self.UIDList[UIDINDEXMASTER], ipcon)
        # Connect to brickd
        ipcon.connect(Parameters["Address"], int(Parameters["Port"]))
        # Don't use device before ipcon is connected
        if state == 0:
            master.disable_status_led()
            Domoticz.Log("Master Status LED disabled.")

        if state == 1:
            master.enable_status_led()
            Domoticz.Log("Master Status LED enabled.")

        ipcon.disconnect()

        return 1

    except:
        # Error
        Domoticz.Log("[ERROR] Can not set Master Status LED.")
        return 0
Exemple #18
0
class MotorPoti:

    UID = "DCx"
    HOST = "localhost"
    PORT = 4223

    def __init__(self):
        self.ipconnection = IPConnection()
        self.mlp = BrickletMotorizedLinearPoti(UID, self.ipconnection)
        self.ipconnection.connect(HOST, PORT)
        self.mlp.register_callback(self.mlp.CALLBACK_POSITION_REACHED,
                                   self.position_reached)

    def position_reached(self, position):
        print("Position: ", position)

    def open_door(self, callback):
        self.mlp.set_motor_position(0, self.mlp.DRIVE_MODE_SMOOTH, False)
        callback("opened")
        print("Opened door")

    def close_door(self, callback):
        self.mlp.set_motor_position(100, self.mlp.DRIVE_MODE_SMOOTH, False)
        callback("closed")
        print("Closed door")
class sound_activated(modes.standard.abstractMode):
    _ipcon = None
    _si = None

    def __init__(self):
        '''
        Constructor
        '''
        modes.standard.abstractMode.__init__(self)
        config = ConfigParser.ConfigParser()
        config.read("config.ini")

        if config.has_section("Tinkerforge") and config.has_option('Tinkerforge', 'HOST') and config.has_option('Tinkerforge', 'PORT') and config.has_option('Tinkerforge', 'UID'):
            HOST = config.get('Tinkerforge', 'HOST')
            PORT = config.getint('Tinkerforge', 'PORT')
            UID = config.get('Tinkerforge', 'UID')
        else:
            print "Can't load Tinkerforge Settings from config.ini"

        self._ipcon = IPConnection()  # Create IP connection
        self._si = SoundIntensity(UID, self._ipcon)  # Create device object

        self._ipcon.connect(HOST, PORT)  # Connect to brickd

    def __del__(self):
        self._ipcon.disconnect()

    def myround(self, x, base=5):
        return int(base * round(float(x) / base))

    def start(self):
        high = 0.0
        count = 0
        while True:
            intensity = self._si.get_intensity()
            # reset high_level after a Song
            if count > 100:
                high = intensity
                count = 0
            if intensity > high:
                high = intensity
            else:
                count += 1
            if high > 0:
                level = self.myround((100 / float(high)) * float(intensity))
            else:
                level = 0

            RED = BLUE = GREEN = 0
            if level <= 33:
                BLUE = 100
            elif level <= 66:
                GREEN = 100
            else:
                RED = 100
            self.setRGB([RED, GREEN, BLUE])
            time.sleep(self._DELAY)

    def getName(self):
        return "Sound Activated"
def ConfigAirQuality(self):
    Domoticz.Debug("ConfigAirQuality - UID:" +
                   self.UIDList[UIDINDEXAIRQUALITY])
    try:
        # Create IP connection
        ipcon = IPConnection()
        # Create device object
        aq = BrickletAirQuality(self.UIDList[UIDINDEXAIRQUALITY], ipcon)
        # Connect to brickd
        ipcon.connect(Parameters["Address"], int(Parameters["Port"]))
        # Don't use device before ipcon is connected

        # Turn off status led
        aq.set_status_led_config(0)
        Domoticz.Log("Air Quality Status LED disabled.")

        # Set temperature offset with resolution 1/100°C. Offset 10 = decrease measured temperature by 0.1°C, 100 = 1°C.
        # offset - int
        # Test with 2°C = 200
        aq.set_temperature_offset(200)

        # The Air Quality Bricklet uses an automatic background calibration mechanism to calculate the IAQ Index.
        # This calibration mechanism considers a history of measured data. Duration history = 4 days (0) or 28 days (1).
        # duration - int 0 | 1
        # Test with 0 = 4 days
        aq.set_background_calibration_duration(0)

        ipcon.disconnect()

        return 1

    except:
        # Error
        Domoticz.Log("[ERROR] Can not set Air Quality Status LED.")
        return 0
        class RedBrickResource:
            def connect(self, uid, host, port):
                self.ipcon = IPConnection()
                self.ipcon.connect(host, port)
                self.rb = BrickRED(uid, self.ipcon)

            def disconnect(self):
                self.ipcon.disconnect()
Exemple #22
0
def main(host, port, uid):
    ipcon = IPConnection()
    rs485 = BrickletRS485(uid, ipcon)
    ipcon.connect(host, port)

    rs485.set_status_led_config(0)
    rs485.set_error_led_config(0)
    rs485.set_communication_led_config(0)
Exemple #23
0
def main(host, port, uid_rs485, uid_master):
    ipcon = IPConnection()
    rs485 = BrickletRS485(uid_rs485, ipcon)
    master = BrickMaster(uid_master, ipcon)
    ipcon.connect(host, port)

    print("get:   " + str(rs485.get_bootloader_mode()))
    print("set 1: " + str(rs485.set_bootloader_mode(1)))
Exemple #24
0
def main(host, port, uid_rs485, uid_master):
    ipcon = IPConnection()
    rs485 = BrickletRS485(uid_rs485, ipcon)
    master = BrickMaster(uid_master, ipcon)
    ipcon.connect(host, port)

    print('Baudrate before: ' + str(master.get_spitfp_baudrate('c')))
    master.set_spitfp_baudrate('c', 2000000)
    print('Baudrate after: ' + str(master.get_spitfp_baudrate('c')))
def connect():
    ipcon = IPConnection() # Create IP connection
    gps = GPS(UID, ipcon) # Create device object

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

    print('GPS Bricklet connected...')
    return gps, ipcon
def connect():
    ipcon = IPConnection()  # Create IP connection
    gps = GPS(UID, ipcon)  # Create device object

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

    print('GPS Bricklet connected...')
    return gps, ipcon
Exemple #27
0
def main(host, port, uid):
    ipcon = IPConnection()
    rs485 = BrickletRS485(uid, ipcon)
    ipcon.connect(host, port)

    t = time.time()
    for _ in range(10000):
        rs485.write("1" * 60, 60)

    print(time.time() - t)
Exemple #28
0
 def setup_connection(self, host):
     ipcon = IPConnection()
     try:
         ipcon.connect(host['name'], host['port'])
         self.log.info("connection to '%s:%s' established", host['name'],
                       host['port'])
     except ConnectionError:
         self.log.error("connection to '%s:%s' failed", host['name'],
                        host['port'])
     self.__connections__.append(ipcon)
     return ipcon
Exemple #29
0
class TinkerforgeConnection(object):
    # Connection to the Brick Daemon on localhost and port 4223
    ipcon = None
    current_entries = dict()

    # noinspection PyUnusedLocal
    def cb_enumerate(self, uid, connected_uid, position, hardware_version, firmware_version, device_identifier,
                     enumeration_type):

        if enumeration_type == IPConnection.ENUMERATION_TYPE_DISCONNECTED:
            del self.current_entries[uid]

        else:
            if device_identifier == 13:
                self.current_entries.update({uid: "Master Brick"})
            elif device_identifier == 21:
                self.current_entries.update({uid: "Ambient Light Bricklet"})
            elif device_identifier == 229:
                self.current_entries.update({uid: "Distance US Bricklet"})
            elif device_identifier == 235:
                self.current_entries.update({uid: "RemoteSwitchBricklet"})
            else:
                self.current_entries.update(
                    {uid: "device_identifier = {0}".format(device_identifier)})

    def switch_socket(self, uid, address, unit, state):
        rs = BrickletRemoteSwitch(uid, self.ipcon)
        rs.switch_socket_b(address, unit, state)

    def dim_socket(self, uid, address, unit, value):
        rs = BrickletRemoteSwitch(uid, self.ipcon)
        rs.dim_socket_b(address, unit, value)

    def get_illuminance(self, uid):
        try:
            al = BrickletAmbientLight(uid, self.ipcon)
            return al.get_illuminance() / 10
        except Exception:
            log.warn(uid + " not connected")
            return -1

    def get_distance(self, uid):
        try:
            dus = BrickletDistanceUS(uid, self.ipcon)
            return dus.get_distance_value()
        except Exception:
            log.warn(uid + " not connected")
            return -1

    def __init__(self, ip_address):
        self.ipcon = IPConnection()
        self.ipcon.connect(ip_address, 4223)
        self.ipcon.register_callback(IPConnection.CALLBACK_ENUMERATE, self.cb_enumerate)
        self.ipcon.enumerate()
Exemple #30
0
def main():
    if len(sys.argv) != 3:
        fail("Usage: {} [UID] [path to firmware.zbin]".format(sys.argv[0]))

    _, uid, plugin_path = sys.argv

    ipcon = IPConnection()
    ipcon.connect("localhost", 4223)
    bricklet = BrickletUnknown(uid, ipcon)
    if write_bricklet_plugin_comcu(plugin_path, bricklet):
        print("Done")
Exemple #31
0
class CheckTFTemperature(object):
    def __init__(self, host='localhost', port=4223):
        self.host = host
        self.port = port
        self.ipcon = IPConnection()

    def connect(self, type, uid):
        self.ipcon.connect(self.host, self.port)
        self.connected_type = type

        if self.connected_type == TYPE_PTC:
            ptc = PTC(uid, self.ipcon)
            self.func = ptc.get_temperature
        elif self.connected_type == TYPE_TEMPERATURE:
            temperature = Temperature(uid, self.ipcon)
            self.func = temperature.get_temperature

    def disconnect(self):
        self.ipcon.disconnect()

    def read_temperature(self):
        return self.func()/100.0

    def read(self, warning, critical, mode='none', warning2=0, critical2=0):
        temp = self.read_temperature()

        if mode == 'none':
            print "temperature %s °C" % temp
        else:
            if mode == 'low':
                warning2 = warning
                critical2 = critical

            if temp >= critical and (mode == 'high' or mode == 'range'):
                print "CRITICAL : temperature too high %s °C" % temp
                return CRITICAL
            elif temp >= warning and (mode == 'high' or mode == 'range'):
                print "WARNING : temperature is high %s °C" % temp
                return WARNING
            elif temp <= critical2 and (mode == 'low' or mode == 'range'):
                print "CRITICAL : temperature too low %s °C" % temp
                return CRITICAL
            elif temp <= warning2 and (mode == 'low' or mode == 'range'):
                print "WARNING : temperature is low %s °C" % temp
                return WARNING
            elif (temp < warning and mode == 'high') or \
                 (temp > warning2 and mode == 'low') or \
                 (temp < warning and temp > warning2 and mode == 'range'):
                print "OK : %s°C " % temp
                return OK
            else:
                print "UNKNOWN : can't read temperature"
                return UNKNOWN
Exemple #32
0
def index():
    ipcon = IPConnection() # Create IP connection
    t = Temperature(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()/100.0

    ipcon.disconnect()
    return PAGE.format(temperature)
Exemple #33
0
class volt_cur:
    def __init__(self):
        self.vc = None

        # Create IP Connection
        self.ipcon = IPConnection() 

        # Register IP Connection callbacks
        self.ipcon.register_callback(IPConnection.CALLBACK_ENUMERATE, 
                                     self.cb_enumerate)
        self.ipcon.register_callback(IPConnection.CALLBACK_CONNECTED, 
                                     self.cb_connected)

        # Connect to brickd, will trigger cb_connected
        self.ipcon.connect(constants.ownIP, PORT) 
        #self.ipcon.enumerate()                 
       
    
    def cb_reached_vc(self):        
        voltage = self.vc.get_voltage()
        dicti = {}
        dicti['value'] = str(voltage)
        dicti['name'] = 'Voltage'
        mySocket.sendto(str(dicti),(constants.server1,constants.broadPort)) 
        mySocket.sendto(str(dicti),(constants.server1,constants.broadPort)) 
        current = self.vc.get_current()
        dicti = {}
        dicti['value'] = str(current)
        dicti['name'] = 'Current'
        mySocket.sendto(str(dicti),(constants.server1,constants.broadPort)) 
        mySocket.sendto(str(dicti),(constants.server1,constants.broadPort))         
        thread_cb_reached = Timer(60, self.cb_reached_vc, [])
        thread_cb_reached.start()        
       
    
    # Callback handles device connections and configures possibly lost 
    # configuration of lcd and temperature callbacks, backlight etc.
    def cb_enumerate(self, uid, connected_uid, position, hardware_version, 
                     firmware_version, device_identifier, enumeration_type):

        if enumeration_type == IPConnection.ENUMERATION_TYPE_CONNECTED or \
           enumeration_type == IPConnection.ENUMERATION_TYPE_AVAILABLE:
            
            # Enumeration for V/C
            if device_identifier == BrickletVoltageCurrent.DEVICE_IDENTIFIER:
                self.vc = BrickletVoltageCurrent(uid, self.ipcon)
                self.cb_reached_vc()
        
    def cb_connected(self, connected_reason):
        # Enumerate devices again. If we reconnected, the Bricks/Bricklets
        # may have been offline and the configuration may be lost.
        # In this case we don't care for the reason of the connection
        self.ipcon.enumerate()    
Exemple #34
0
class volt_cur:
    def __init__(self):
        self.vc = None

        # Create IP Connection
        self.ipcon = IPConnection()

        # Register IP Connection callbacks
        self.ipcon.register_callback(IPConnection.CALLBACK_ENUMERATE,
                                     self.cb_enumerate)
        self.ipcon.register_callback(IPConnection.CALLBACK_CONNECTED,
                                     self.cb_connected)

        # Connect to brickd, will trigger cb_connected
        self.ipcon.connect(constants.ownIP, PORT)
        #self.ipcon.enumerate()

    def cb_reached_vc(self):
        voltage = self.vc.get_voltage()
        dicti = {}
        dicti['value'] = str(voltage)
        dicti['name'] = 'Voltage'
        mySocket.sendto(str(dicti), (constants.server1, constants.broadPort))
        mySocket.sendto(str(dicti), (constants.server1, constants.broadPort))
        current = self.vc.get_current()
        dicti = {}
        dicti['value'] = str(current)
        dicti['name'] = 'Current'
        mySocket.sendto(str(dicti), (constants.server1, constants.broadPort))
        mySocket.sendto(str(dicti), (constants.server1, constants.broadPort))
        thread_cb_reached = Timer(60, self.cb_reached_vc, [])
        thread_cb_reached.start()

    # Callback handles device connections and configures possibly lost
    # configuration of lcd and temperature callbacks, backlight etc.
    def cb_enumerate(self, uid, connected_uid, position, hardware_version,
                     firmware_version, device_identifier, enumeration_type):

        if enumeration_type == IPConnection.ENUMERATION_TYPE_CONNECTED or \
           enumeration_type == IPConnection.ENUMERATION_TYPE_AVAILABLE:

            # Enumeration for V/C
            if device_identifier == BrickletVoltageCurrent.DEVICE_IDENTIFIER:
                self.vc = BrickletVoltageCurrent(uid, self.ipcon)
                self.cb_reached_vc()

    def cb_connected(self, connected_reason):
        # Enumerate devices again. If we reconnected, the Bricks/Bricklets
        # may have been offline and the configuration may be lost.
        # In this case we don't care for the reason of the connection
        self.ipcon.enumerate()
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
Exemple #36
0
 def run(self):
     global ipcon
     isexception = False
     try:
         ipcon = IPConnection()
         if ipcon.get_connection_state(
         ) != IPConnection.CONNECTION_STATE_CONNECTED:
             ipcon.connect("localhost", 4223)
             ipcon.register_callback(IPConnection.CALLBACK_ENUMERATE,
                                     cb_enumerate)
             ipcon.time_out = 0.5
         ipcon.enumerate()
         time.sleep(0.3)
     except:
         logging.debug("Tinkerforge:failed connecting to IP Connection")
         pass
	def __init__(self):
		#uinput Bereich
		self.events = (
			uinput.BTN_A, #Es wird mindestens ein Button benötigt (seltsam)
			uinput.ABS_Z + (-150, 150, 0, 0), #Erstellt Joystick Achse Z, kleinster Wert des Potis ist -150, größter Wert ist +150
			)

		self.device = uinput.Device(self.events, "TF Virutal HID Joystick")
		
		#TinkerForge Bereich
		ipcon = IPConnection()
		self.poti = RotaryPoti("aBQ", ipcon) #UID ändern!

		ipcon.connect("127.0.0.1", 4223) #IP / Port anpassen
		self.poti.set_position_callback_period(50)
		self.poti.register_callback(self.poti.CALLBACK_POSITION, self.poti_cb) #Sobald der Callback auslöst wird die Funktion poti_cb aufgerufen
def getTFconn( HOST=TF_HOST, PORT=TF_PORT ):
    try:
        ipcon = IPConnection()
    except  Exception as e:
        errmsg = str(traceback.format_exception( *sys.exc_info() ));
        Logger.info( 'Tinkerforge IPConnection failed ... ' + errmsg );
        sendEmail(admin,'getPower.py', 'Tinkerforge IPConnection failed ... ' + errmsg )
        sys.exit(-1) # should cause rPi to reboot
    try:
        ipcon.connect(HOST, PORT)
    except  Exception as e:
        errmsg = str(traceback.format_exception( *sys.exc_info() ));
        Logger.info( 'Tinkerforge unable to connect! ' + errmsg );
        sendEmail(admin,'getPower.py', 'Tinkerforge unable to connect! ' + errmsg )
        sys.exit(-1) # should cause rPi to reboot
    return ipcon
def index():
    ipcon = IPConnection() # Create IP connection
    humidity_bricklet = BrickletHumidityV2(HUMIDITY_UID, ipcon) # Create device object
    barometer_bricklet = BrickletBarometer(BAROMETER_UID, ipcon)
    ambient_light_bricklet = BrickletAmbientLightV2(AMBIENT_LIGHT_UID, ipcon)

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

    temperature = humidity_bricklet.get_temperature()/100.0
    humidity = humidity_bricklet.get_humidity()/100.0
    air_pressure = barometer_bricklet.get_air_pressure()/1000.0
    illuminance = ambient_light_bricklet.get_illuminance()/100.0

    ipcon.disconnect()
    return render_template('index.html', temperature=temperature, humidity=humidity, illuminance=illuminance, air_pressure=air_pressure)
Exemple #40
0
def main(host, port, uid1, uid2, uid3, uid_master):
    ipcon = IPConnection()
    rs4851 = BrickletRS485(uid1, ipcon)
    rs4852 = BrickletRS485(uid2, ipcon)
    rs4853 = BrickletRS485(uid3, ipcon)
    master = BrickMaster(uid_master, ipcon)
    ipcon.connect(host, port)

    while True:
        print('RS485-1: ' + str(rs4851.get_spitfp_error_count()))
        print('RS485-2: ' + str(rs4852.get_spitfp_error_count()))
        print('RS485-3: ' + str(rs4853.get_spitfp_error_count()))
        print('Master-a: ' + str(master.get_spitfp_error_count('a')))
        print('Master-b: ' + str(master.get_spitfp_error_count('b')))
        print('Master-c: ' + str(master.get_spitfp_error_count('c')))
        time.sleep(1)
Exemple #41
0
class dist_us:
    def __init__(self):
        self.dus = None

        # Create IP Connection
        self.ipcon = IPConnection() 

        # Register IP Connection callbacks
        self.ipcon.register_callback(IPConnection.CALLBACK_ENUMERATE, 
                                     self.cb_enumerate)
        self.ipcon.register_callback(IPConnection.CALLBACK_CONNECTED, 
                                     self.cb_connected)

        # Connect to brickd, will trigger cb_connected
        self.ipcon.connect(constants.ownIP, PORT) 
        #self.ipcon.enumerate()                 
       
    
    def cb_distance(self, distance):        
        dicti = {}
        dicti['value'] = str(distance)
        dicti['name'] = str(self.dus.get_identity()[0]) + "_" + str(self.dus.get_identity()[5])
        mySocket.sendto(str(dicti),(constants.server1,constants.broadPort)) 
        mySocket.sendto(str(dicti),(constants.server1,constants.broadPort)) 
       
    
    # Callback handles device connections and configures possibly lost 
    # configuration of lcd and temperature callbacks, backlight etc.
    def cb_enumerate(self, uid, connected_uid, position, hardware_version, 
                     firmware_version, device_identifier, enumeration_type):

        if enumeration_type == IPConnection.ENUMERATION_TYPE_CONNECTED or \
           enumeration_type == IPConnection.ENUMERATION_TYPE_AVAILABLE:
            
            # Enumeration for Distance US
            if device_identifier == BrickletDistanceUS.DEVICE_IDENTIFIER:
                self.dus = BrickletDistanceUS(uid, self.ipcon)
                self.dus.register_callback(self.dus.CALLBACK_DISTANCE, self.cb_distance)
                self.dus.set_distance_callback_period(10000)

        
    def cb_connected(self, connected_reason):
        # Enumerate devices again. If we reconnected, the Bricks/Bricklets
        # may have been offline and the configuration may be lost.
        # In this case we don't care for the reason of the connection
        self.ipcon.enumerate()          
def main(host, port, uid):
    ipcon = IPConnection()
    rs485 = BrickletRS485(uid, ipcon)
    ipcon.connect(host, port)

    t = time.time()
    i = 0
    while True:
        i += 1
        nt = time.time()
        if nt - t >= 1.0:
            print(i)
            i = 0
            t = nt
        rs485.get_chip_temperature()

    print(time.time() - t)
Exemple #43
0
def read_data(fake=None):
    """ Reads data from all weather sensors and returns it as Dictionary.
        In case of an error or outlier None is returned"""
    if fake:
        return weather_data

    try:
        ipcon = IPConnection()
        temp_bricklet = Temperature('qnk', ipcon)
        humidity_bricklet = Humidity('nLC', ipcon)
        barometer_bricklet = Barometer('k5g', ipcon)
        ipcon.connect(cfg['weather']['host'], int(cfg['weather']['port']))
        temp_bricklet.set_i2c_mode(Temperature.I2C_MODE_SLOW)

        temp = temp_bricklet.get_temperature() / 100.0
        if 45 < temp < -30:
            weather_data['temperature'] = None
            logger.warn(
                'Got temperature value of %s Grade which is out of range' %
                temp)
        else:
            weather_data['temperature'] = temp

        humidity = humidity_bricklet.get_humidity() / 10.0
        if humidity < 5:
            weather_data['humidity'] = None
            logger.warn('Got humidity value of %s RH which is out of range' %
                        humidity)
        else:
            weather_data['humidity'] = humidity

        pressure = barometer_bricklet.get_air_pressure() / 1000.0
        if 1080 < pressure < 930:
            weather_data['pressure'] = None
            logger.warn('Got pressure value of %s mbar which is out of range' %
                        pressure)
        else:
            weather_data['pressure'] = pressure

        ipcon.disconnect()
        return weather_data

    except Exception as e:
        logger.error('Cloud not connect to weather sensors: %s' % str(e))
        return
Exemple #44
0
class dist_us:
    def __init__(self):
        self.dus = None

        # Create IP Connection
        self.ipcon = IPConnection()

        # Register IP Connection callbacks
        self.ipcon.register_callback(IPConnection.CALLBACK_ENUMERATE,
                                     self.cb_enumerate)
        self.ipcon.register_callback(IPConnection.CALLBACK_CONNECTED,
                                     self.cb_connected)

        # Connect to brickd, will trigger cb_connected
        self.ipcon.connect(constants.ownIP, PORT)
        #self.ipcon.enumerate()

    def cb_distance(self, distance):
        dicti = {}
        dicti['value'] = str(distance)
        dicti['name'] = str(self.dus.get_identity()[0]) + "_" + str(
            self.dus.get_identity()[5])
        mySocket.sendto(str(dicti), (constants.server1, constants.broadPort))
        mySocket.sendto(str(dicti), (constants.server1, constants.broadPort))

    # Callback handles device connections and configures possibly lost
    # configuration of lcd and temperature callbacks, backlight etc.
    def cb_enumerate(self, uid, connected_uid, position, hardware_version,
                     firmware_version, device_identifier, enumeration_type):

        if enumeration_type == IPConnection.ENUMERATION_TYPE_CONNECTED or \
           enumeration_type == IPConnection.ENUMERATION_TYPE_AVAILABLE:

            # Enumeration for Distance US
            if device_identifier == BrickletDistanceUS.DEVICE_IDENTIFIER:
                self.dus = BrickletDistanceUS(uid, self.ipcon)
                self.dus.register_callback(self.dus.CALLBACK_DISTANCE,
                                           self.cb_distance)
                self.dus.set_distance_callback_period(10000)

    def cb_connected(self, connected_reason):
        # Enumerate devices again. If we reconnected, the Bricks/Bricklets
        # may have been offline and the configuration may be lost.
        # In this case we don't care for the reason of the connection
        self.ipcon.enumerate()
    def __init__(self, parent=None):
        QMainWindow.__init__(self, parent)

        self.initialized = False
        self.altitude_error_i = 0
        self.acc_scale  = 0.0
        self.start_time = time.time()
        self.altitude_error = 0
        self.inst_acceleration = 0.0
        self.delta = 0
        self.estimated_velocity = 0.0
        self.estimated_altitude = 0.0
        self.last_time = time.time()

        self.last_orig_altitude = 0
        self.last_estimated_altitude = 0

        ipcon = IPConnection() 
        self.imu = IMU(UID_IMU, ipcon) 
        self.barometer = Barometer(UID_BAROMETER, ipcon)
        ipcon.connect(HOST, PORT) 

        # Turn leds and orientation calculation off, to save calculation time
        # for the IMU Brick. This makes sure that the measurements are taken
        # in equidistant 2ms intervals
        self.imu.leds_off()
        self.imu.orientation_calculation_off()

        # Turn averaging of in the Barometer Bricklet to make sure that
        # the data is without delay
        self.barometer.set_averaging(0, 0, 0)

        red_pen = QPen(Qt.red)
        red_pen.setWidth(5)

        plot_list = [#['', Qt.blue, self.get_orig_value],
                     ['', red_pen, self.get_estimated_value]
                    ]
        self.plot_widget = PlotWidget('Height [m]', plot_list)
        self.plot_widget.stop = False
        self.setCentralWidget(self.plot_widget)

        self.timer = QTimer()
        self.timer.timeout.connect(self.update)
        self.timer.start(6)
Exemple #46
0
def get_airpressure(id):
    
    cfg = configparser.ConfigParser()
    
    cfg.read(cfg_filename) # open config file to read from
    
    if cfg.has_section("Barometer") == True:
    
        port = cfg.getint('Connection', 'Port') # get port entry from config file
        
        host = cfg.get('Connection', 'Host') # get host entry from config file
        
        uid = cfg.get('Barometer', 'bricklet_uid') # uid port entry from config file
        
        ipcon = IPConnection() # Create IP connection
        
        ipcon.connect(host, port) # Connect to brickd
        
        b = Barometer(uid, ipcon) # Create device object
        
        air_pressure = b.get_air_pressure()/1000.0 # Get current air pressure (unit is mbar/1000)
        
        altitude = b.get_altitude()/100.0
        
        db = sqlite3.connect(local_db) # build connection to local database
        
        c = db.cursor() # create cursor
        
        c.execute(wd_table) # create weatherdata table
        
        c.execute('''INSERT INTO weatherdata(uid , value, keyword, date_id, device_name) VALUES(?,?,?,?,?)''', (uid,air_pressure,'air_pressure',id,'barometer',))
        # insert the uid, device name the id from the date table an die humdity value into the weather table
        
        c.execute('''INSERT INTO weatherdata(uid , value, keyword, date_id, device_name) VALUES(?,?,?,?,?)''', (uid,altitude,'altitude',id,'barometer',))
        
        db.commit() # save creates and inserts permanent  

        ipcon.disconnect()
    
        return({"air_pressure": air_pressure, "altitude": altitude})
def discover():
    HOST = "localhost"
    PORT = 4223
    global ipcon
    ipcon = IPConnection()
    ipcon.register_callback(IPConnection.CALLBACK_CONNECTED, cb_connected)
    ipcon.register_callback(IPConnection.CALLBACK_ENUMERATE, cb_enumerate)
    try:
        ipcon.connect(HOST, PORT)
        w = threading.Thread(target=wait)
        w.start()
        w.join()
        print("baromenter id: " + str(barometerid))
        print("humidity id: " + str(humidityid))
        print("ambient id: " + str(ambientid))
        print("lcd id: " + str(lcdid))
        
        ipcon.disconnect()
    except socket.error, e:
        global discovery_timed_out
        discovery_timed_out = True
        print("Error: ipconnection failed " + str(e))
Exemple #48
0
def get_humidity(id):
    
    cfg = configparser.ConfigParser()
    
    cfg.read(cfg_filename) # open config file to read from
    
    port = cfg.getint('Connection', 'Port') # get port entry from config file
    
    host = cfg.get('Connection', 'Host') # get host entry from config file
    
    uid = cfg.get('Humidity', 'bricklet_uid') # uid port entry from config file
    
    ipcon = IPConnection() # Create IP connection
    
    ipcon.connect(host, port) # Connect to brickd
    
    h = Humidity(uid, ipcon) # Create device object
    
    rh = h.get_humidity()/10.0 # Get current humidity (unit is %RH/10)
    
    db = sqlite3.connect(local_db) # build connection to local database
    
    c = db.cursor() # create cursor
    
    c.execute(wd_table) # create weatherdata table
    
    c.execute('''INSERT INTO weatherdata(uid , value, keyword, date_id, device_name) VALUES(?,?,?,?,?)''', (uid,rh,'rel. humidity', id,'humidity',))
    # insert the uid, device name the id from the date table an die humdity value into the weather table
    
    db.commit() # save creates and inserts permanent  
    
    print()
    print('Relative Humidity: ' + str(rh) + ' %RH')
    print()
        
    ipcon.disconnect()

    return(rh)
Exemple #49
0
def read_data():
    try:
        ipcon = IPConnection()
        temp_bricklet = Temperature('qnk', ipcon)
        humidity_bricklet = Humidity('nLC', ipcon)
        barometer_bricklet = Barometer('k5g', ipcon)
        ipcon.connect(cfg['weather']['host'], int(cfg['weather']['port']))
        temp_bricklet.set_i2c_mode(Temperature.I2C_MODE_SLOW)

        temp = temp_bricklet.get_temperature() / 100.0
        if 45 < temp < -30:
            weather_data['temperature'] = None
            logger.warn('Got temperature value of %s Grade which is out of range' % temp)
        else:
            weather_data['temperature'] = temp

        humidity = humidity_bricklet.get_humidity() / 10.0
        if humidity < 5:
            weather_data['humidity'] = None
            logger.warn('Got humidity value of %s RH which is out of range' % humidity)
        else:
            weather_data['humidity'] = humidity

        pressure = barometer_bricklet.get_air_pressure() / 1000.0
        if 1090 < pressure < 920:
            weather_data['pressure'] = None
            logger.warn('Got pressure value of %s mbar which is out of range' % pressure)
        else:
            weather_data['pressure'] = pressure

        ipcon.disconnect()
        return weather_data

    except Exception as e:
        logger.error('Cloud not connect to weather sensors: %s' % str(e))
        return
Exemple #50
0
class WeatherStation(QApplication):
    HOST = "localhost"
    PORT = 4223

    ipcon = None
    lcd = None
    al = None
    hum = None
    baro = None

    projects = []
    active_project = None

    error_msg = None

    def __init__(self, args):
        super(QApplication, self).__init__(args)

        self.error_msg = QErrorMessage()
        self.ipcon = IPConnection()

        signal.signal(signal.SIGINT, self.exit_demo)
        signal.signal(signal.SIGTERM, self.exit_demo)

        timer = QTimer(self)
        timer.setSingleShot(True)
        timer.timeout.connect(self.connect)
        timer.start(1)

    def exit_demo(self, signl=None, frme=None):
        try:
            self.ipcon.disconnect()
            self.timer.stop()
            self.tabs.destroy()
        except:
            pass

        sys.exit()

    def open_gui(self):
        self.main = MainWindow(self)
        self.main.setFixedSize(730, 430)
        self.main.setWindowIcon(QIcon(os.path.join(ProgramPath.program_path(), "demo-icon.png")))
        
        self.tabs = QTabWidget()
        
        widget = QWidget()
        layout = QVBoxLayout()
        layout.addWidget(self.tabs)
        widget.setLayout(layout)

        self.main.setCentralWidget(widget)
        
        self.projects.append(ProjectEnvDisplay(self.tabs, self))
        self.projects.append(ProjectStatistics(self.tabs, self))
        self.projects.append(ProjectXively(self.tabs, self))

        self.tabs.addTab(self.projects[0], "Display Environment Measurements")
        self.tabs.addTab(self.projects[1], "Show Statistics with Button Control")
        self.tabs.addTab(self.projects[2], "Connect to Xively")

        self.active_project = self.projects[0]

        self.tabs.currentChanged.connect(self.tabChangedSlot)

        self.main.setWindowTitle("Starter Kit: Weather Station Demo " + config.DEMO_VERSION)
        self.main.show()

    def connect(self):
        try:
            self.ipcon.connect(WeatherStation.HOST, WeatherStation.PORT)
        except Error as e:
            self.error_msg.showMessage('Connection Error: ' + str(e.description) + "\nBrickd installed and running?")
            return
        except socket.error as e:
            self.error_msg.showMessage('Socket error: ' + str(e) + "\nBrickd installed and running?")
            return

        self.ipcon.register_callback(IPConnection.CALLBACK_ENUMERATE,
                                     self.cb_enumerate)
        self.ipcon.register_callback(IPConnection.CALLBACK_CONNECTED,
                                     self.cb_connected)

        try:
            self.ipcon.enumerate()
        except Error as e:
            self.error_msg.showMessage('Enumerate Error: ' + str(e.description))
            return

        self.open_gui()

    def tabChangedSlot(self, tabIndex):

        if self.lcd is not None:
            self.lcd.clear_display()

        self.active_project = self.projects[tabIndex]

    def cb_illuminance(self, illuminance):
        for p in self.projects:
            p.update_illuminance(illuminance)

    def cb_humidity(self, humidity):
        for p in self.projects:
            p.update_humidity(humidity)

    def cb_air_pressure(self, air_pressure):
        for p in self.projects:
            p.update_air_pressure(air_pressure)

        try:
            temperature = self.baro.get_chip_temperature()
        except Error as e:
            print('Could not get temperature: ' + str(e.description))
            return

        for p in self.projects:
            p.update_temperature(temperature)

    def configure_custom_chars(self):
        c = [[0x00 for x in range(8)] for y in range(8)]
	
        c[0] = [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff]
        c[1] = [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff]
        c[2] = [0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff]
        c[3] = [0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff]
        c[4] = [0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff]
        c[5] = [0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff]
        c[6] = [0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff]
        c[7] = [0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff]

        for i in range(len(c)):
            self.lcd.set_custom_character(i, c[i]);

    def cb_button_pressed(self, button):
        for p in self.projects:
            p.button_pressed(button)

    def cb_enumerate(self, uid, connected_uid, position, hardware_version,
                     firmware_version, device_identifier, enumeration_type):
        if enumeration_type == IPConnection.ENUMERATION_TYPE_CONNECTED or \
           enumeration_type == IPConnection.ENUMERATION_TYPE_AVAILABLE:
            if device_identifier == LCD20x4.DEVICE_IDENTIFIER:
                try:
                    self.lcd = LCD20x4(uid, self.ipcon)
                    self.lcd.clear_display()
                    self.lcd.backlight_on()
                    self.lcd.register_callback(self.lcd.CALLBACK_BUTTON_PRESSED, self.cb_button_pressed)
                    self.configure_custom_chars()

                except Error as e:
                    self.error_msg.showMessage('LCD 20x4 init failed: ' + str(e.description))
                    self.lcd = None
            elif device_identifier == AmbientLight.DEVICE_IDENTIFIER:
                try:
                    self.al = AmbientLight(uid, self.ipcon)
                    self.al.set_illuminance_callback_period(1000)
                    self.al.register_callback(self.al.CALLBACK_ILLUMINANCE,
                                              self.cb_illuminance)
                except Error as e:
                    self.error_msg.showMessage('Ambient Light init failed: ' + str(e.description))
                    self.al = None
            elif device_identifier == Humidity.DEVICE_IDENTIFIER:
                try:
                    self.hum = Humidity(uid, self.ipcon)
                    self.hum.set_humidity_callback_period(1000)
                    self.hum.register_callback(self.hum.CALLBACK_HUMIDITY,
                                               self.cb_humidity)
                except Error as e:
                    self.error_msg.showMessage('Humidity init failed: ' + str(e.description))
                    self.hum = None
            elif device_identifier == Barometer.DEVICE_IDENTIFIER:
                try:
                    self.baro = Barometer(uid, self.ipcon)
                    self.baro.set_air_pressure_callback_period(1000)
                    self.baro.register_callback(self.baro.CALLBACK_AIR_PRESSURE,
                                                self.cb_air_pressure)
                except Error as e:
                    self.error_msg.showMessage('Barometer init failed: ' + str(e.description))
                    self.baro = None

    def cb_connected(self, connected_reason):
        if connected_reason == IPConnection.CONNECT_REASON_AUTO_RECONNECT:

            while True:
                try:
                    self.ipcon.enumerate()
                    break
                except Error as e:
                    self.error_msg.showMessage('Enumerate Error: ' + str(e.description))
                    time.sleep(1)
#!/usr/bin/env python
# -*- coding: utf-8 -*-

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

from tinkerforge.ip_connection import IPConnection
from tinkerforge.bricklet_current12 import BrickletCurrent12

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

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

    # Get current current (unit is mA)
    current = c.get_current()
    print("Current: " + str(current / 1000.0) + " A")

    raw_input("Press key to exit\n")  # Use input() in Python 3
    ipcon.disconnect()
class master():
    """docstring for master"""
    def __init__(self):
        #super(master, self).__init__()
        print 'init...'
        self.PORT   = 4223
        self.MENU_running = False
        self.BOARD_running = False

        ### Connection for Menu
        self.MENU_HOST   = "192.168.0.150" # Manually Set IP of Controller Board
        self.MENU_lcdUID = "gFt" # LCD Screen
        self.MENU_jskUID = "hAP" # Joystick
        ### END MENU CONNECTION

        ### Connection for Board
        self.BOARD_HOST   = "192.168.0.111"
        self.BOARD_mstUID = "62eUEf" # master brick
        self.BOARD_io1UID = "ghh"    # io16
        self.BOARD_lcdUID = "9ew"    # lcd screen 20x4
        self.BOARD_iqrUID = "eRN"    # industrial quad relay
        #### END BOARD CONNECTION

        return
        
    def start(self):
        if self.BOARD_running: print 'Board already running!'
        else: self.startBoard(); print 'Board Started!'

        if self.MENU_running: print 'Menu already running!'
        else: self.startMenu(); print 'Menu Started!'
        return 'Started!'

    def status(self):
        return 'Board: '+str(self.BOARD_running)+'\nMenu: '+str(self.MENU_running)
    
    def startBoard(self):
        if self.BOARD_running: return 'Board already running!'

        if isOpen(self.BOARD_HOST, self.PORT):
            
            self.BOARD_running = True

            self.BOARD_ipcon = IPConnection() # Create IP connection

            self.mst = Master(self.BOARD_mstUID, self.BOARD_ipcon)   # Master Brick
            self.io1 = IO16(self.BOARD_io1UID, self.BOARD_ipcon)       # io16
            self.lcd1 = LCD20x4(self.BOARD_lcdUID, self.BOARD_ipcon)  # lcd20x4
            self.iqr = IndustrialQuadRelay(self.BOARD_iqrUID, self.BOARD_ipcon) # Create device object

            self.BOARD_ipcon.connect(self.BOARD_HOST, self.PORT) # Connect to brickd
            
            # create Board instance 
            self.BB = B(self.mst, self.io1, self.lcd1, self.iqr, self.BOARD_ipcon)        
        else:
            return 'Board is offline'
        return "Hello, Board successfully started!"
    
    def startMenu(self):
        if self.MENU_running: return 'Menu already running!'

        if isOpen(self.MENU_HOST, self.PORT):

            self.MENU_running = True

            # Connect to WLAN Controller
            self.MENU_ipcon = IPConnection() # Create IP connection

            self.lcd = LCD20x4(self.MENU_lcdUID, self.MENU_ipcon) # Create device object LCD
            self.jsk = Joystick(self.MENU_jskUID, self.MENU_ipcon) # Create device object JOYSTICK
            
            # Don't use device before ipcon is connected
            self.MENU_ipcon.connect(self.MENU_HOST, self.PORT) # Connect to brickd

            # create Menu instance with the nessesary Hardware # IPCON to close Tinker Connection
            self.MM = M(self.jsk, self.lcd, self.MENU_ipcon) 
        else:
            return 'Menu is offline'  

        return "Hello, Menu successfully started!"

    def stop(self):
        print 'stopping devices...'
        if self.MENU_running: 
            self.MENU_running = False
            self.MM.quit()
        if self.BOARD_running:
            self.BOARD_running = False
            self.BB.quit()    # Stop Board
        #quit()
        return 'successfully stopped'        
Exemple #53
0
                except:
                    break
        else:
            try:
                self.led_strip.set_led_values(0, frame)
            except:
                return

    def frame_prepare_next(self):
        if len(self.images) == 0:
            return

        self.leds = self.images[self.image_position]
        self.image_position = (self.image_position + 1) % len(self.images)


if __name__ == "__main__":
    # Create IP Connection and connect it
    ipcon = IPConnection()
    ipcon.connect(config.HOST, config.PORT)

    # Create Images object and start rendering
    images = Images(ipcon)

    images.set_new_images(sys.argv[1:])
    images.frame_rendered(0)

    raw_input('Press enter to exit\n') # Use input() in Python 3

    ipcon.disconnect()
Exemple #54
0
class tiFo:
    
    r = [0]*16
    g = [0]*16
    b = [0]*16
    
    def __init__(self):
        self.led = None
        self.io = []
        self.io16list = io16Dict()
        self.LEDs = []
        self.LEDList = LEDStrips()
        self.al = []
        self.drb = []
        self.master = []
        self.md = []
        self.si = []
        self.ptc = []
        self.co2 = []
        self.moist = None
        # Create IP Connection
        self.ipcon = IPConnection() 
        # Register IP Connection callbacks
        self.ipcon.register_callback(IPConnection.CALLBACK_ENUMERATE, 
                                     self.cb_enumerate)
        self.ipcon.register_callback(IPConnection.CALLBACK_CONNECTED, 
                                     self.cb_connected)
        # Connect to brickd, will trigger cb_connected
        self.ipcon.connect(constants.ownIP, PORT) 
        self.unknown = []
        self.threadliste = []
        #self.ipcon.enumerate()        

    def thread_RSerror(self):
        for mastr in self.master:    
            print mastr.get_rs485_error_log()
        thread_rs_error = Timer(60, self.thread_RSerror, [])
        thread_rs_error.start()         

    def cb_ambLight(self, illuminance,device):
        thresUp = illuminance * 4/3
        thresDown = illuminance * 4 / 5
        if thresDown == 0:
            thresDown = 0
            thresUp = 3
        if thresUp > 9000:
            thresUp = 9000            
        #print illuminance, thresDown, thresUp
        device.set_illuminance_callback_threshold('o', thresDown, thresUp)
        dicti = {}
        name = tifo_config.inputs.get(str(device.get_identity()[1]) +"."+ str(device.get_identity()[0]))
        name = str(device.get_identity()[1]) +"."+ str(device.get_identity()[0])
        dicti['Value'] = str(illuminance)
        dicti['Name'] = 'TiFo.' + name
        #print dicti
        mySocket.sendto(str(dicti) ,(constants.server1,constants.broadPort))
        
    def thread_ambLight(self, device):
        illuminance = device.get_illuminance()
        dicti = {}
        name = tifo_config.inputs.get(str(device.get_identity()[1]) +"."+ str(device.get_identity()[0]))
        name = str(device.get_identity()[1]) +"."+ str(device.get_identity()[0])
        dicti['Value'] = str(illuminance)
        dicti['Name'] = 'TiFo.' + name
        #print dicti
        mySocket.sendto(str(dicti) ,(constants.server1,constants.broadPort))
        thread_cb_amb = Timer(60, self.thread_ambLight, [device])
        thread_cb_amb.start()        

    def thread_CO2(self, device):
        value = device.get_co2_concentration()
        dicti = {}
        name = tifo_config.inputs.get(str(device.get_identity()[1]) +"."+ str(device.get_identity()[0]))
        name = str(device.get_identity()[1]) +"."+ str(device.get_identity()[0])
        dicti['Value'] = str(value)
        dicti['Name'] = 'TiFo.' + name
        mySocket.sendto(str(dicti) ,(constants.server1,constants.broadPort))
        thread_co2_ = Timer(60, self.thread_CO2, [device])
        thread_co2_.start()

    def thread_pt(self, device):
        value = device.get_temperature()
        dicti = {}
        name = tifo_config.inputs.get(str(device.get_identity()[1]) +"."+ str(device.get_identity()[0]))
        name = str(device.get_identity()[1]) +"."+ str(device.get_identity()[0])
        dicti['Value'] = str(float(value)/100)
        dicti['Name'] = 'TiFo.' + name
        mySocket.sendto(str(dicti) ,(constants.server1,constants.broadPort))
        thread_pt_ = Timer(60, self.thread_pt, [device])
        thread_pt_.start()

    def cb_interrupt(self, port, interrupt_mask, value_mask, device, uid):
        #print('Interrupt on port: ' + port + str(bin(interrupt_mask)))
        #print('Value: ' + str(bin(value_mask)))
        namelist = []
        temp_uid = uid #str(device.get_identity()[1]) +"."+ str(device.get_identity()[0])
        bit_list = [(1 << bit) for bit in range(7, -1, -1)]
        for wert in bit_list:
            if interrupt_mask & wert > 0:
                name = tifo_config.IO16i.get(temp_uid).get(port + str(bin(wert)))
                name = temp_uid + "." + port + str(bin(wert))
                if name <> None:
                    namelist.append(name)
        if port == 'a':
            nc_mask = tifo_config.IO16.get(temp_uid)[7]
        else:
            nc_mask = tifo_config.IO16.get(temp_uid)[8]
        value = (value_mask&interrupt_mask)/interrupt_mask
        nc_pos = (nc_mask&interrupt_mask)/interrupt_mask
        dicti = {}
#        dicti['Name'] = name
#        dicti['temp_uid'] = temp_uid
#        dicti['name'] = port + str(bin(interrupt_mask))
        #print name, value
        self.io16list.setValues(device,value_mask,port)
        #print self.io16list.getTimeDiff(device,interrupt_mask, port)
        if value == nc_pos:        
            dicti['Value'] = self.io16list.getTimeDiff(device,interrupt_mask, port)
        else:
            dicti['Value'] = 0
            self.io16list.setTime(device,interrupt_mask, port)
        #print dicti
        for name in namelist:
            dicti['Name'] = 'TiFo.' + name
            mySocket.sendto(str(dicti) ,(constants.server1,constants.broadPort))       

    def cb_md(self, device, uid):
        dicti = {'Name':tifo_config.inputs.get(uid),'Value':1}
        dicti = {'Name':'TiFo.' + str(device.get_identity()[1]) +"."+ str(device.get_identity()[0]),'Value':1}
        mySocket.sendto(str(dicti) ,(constants.server1,constants.broadPort))
        
    def cb_md_end(self, device, uid):
        dicti = {'Name':tifo_config.inputs.get(uid),'Value':0}
        dicti = {'Name':'TiFo.' + str(device.get_identity()[1]) +"."+ str(device.get_identity()[0]),'Value':0}
        mySocket.sendto(str(dicti) ,(constants.server1,constants.broadPort))      

    def cb_si(self,value, device, uid):
        dicti = {'Name':tifo_config.inputs.get(uid),'Value':value}
        dicti = {'Name':'TiFo.' + str(device.get_identity()[1]) +"."+ str(device.get_identity()[0]),'Value':value}
        mySocket.sendto(str(dicti) ,(constants.server1,constants.broadPort)) 

    def set_io16_sub(self,cmd,io,value):
        port = cmd.get('Port') 
        if port  == 'A':
            flopmask = tifo_config.IO16.get(io.get('addr'))[4]
            if flopmask & cmd.get('Pin') > 0:
                if value == 1:
                    normpos = tifo_config.IO16.get(io.get('addr'))[7]
                    io.get('IO').set_port_monoflop('a', cmd.get('Pin'),((~normpos)&0b11111111),tifo_config.IO16.get(io.get('addr'))[6])
            else:
                if value == 1:
                    mask = io.get('valueA') | cmd.get('Pin')
                else:
                    mask = io.get('valueA') & (0b11111111 & ~ cmd.get('Pin'))
                self.io16list.setValues(io.get('IO'),mask,'a')
                io.get('IO').set_port('a',mask)
        else:
            flopmask = tifo_config.IO16.get(io.get('addr'))[5]
            if flopmask & cmd.get('Pin') > 0:
                if value == 1:
                    #working but gets overwritten but other commands
#                    normpos = tifo_config.IO16.get(io.get('addr'))[8]
#                    io.get('IO').set_port_monoflop('b', cmd.get('Pin'),((~normpos)&0b11111111),tifo_config.IO16.get(io.get('addr'))[6]) 
                    mask = io.get('IO').get_port('b') | cmd.get('Pin')
                    io.get('IO').set_port('b',mask)
                    time.sleep(float(tifo_config.IO16.get(io.get('addr'))[6])/1000)
                    mask = io.get('IO').get_port('b') & (0b11111111 & ~ cmd.get('Pin'))
                    io.get('IO').set_port('b',mask)   
            else:
                if value == 1:
                    mask = io.get('IO').get_port('b') | cmd.get('Pin')
                else:
                    mask = io.get('IO').get_port('b') & (0b11111111 & ~ cmd.get('Pin'))
                self.io16list.setValues(io.get('IO'),mask,'b')
                io.get('IO').set_port('b',mask)       

    def set_io16(self,device,value):
        #koennte noch auch .set_selected_values(port, selection_mask, value_mask) umgeschrieben werden
        #monoflop tut nicht
        cmd_lsts = tifo_config.IO16o.get(device)
        for cmd in cmd_lsts:
            if cmd.get('Value') == value:
                cmds = cmd.get('Commands')
                #print cmds
                if type(cmds) in (list,tuple):
                    for cmd in cmds:
                        #print cmd
                        if cmd.get('Value') == 0: #erst alle auf Null setzen
                            addr = cmd.get('UID') 
                            for io in self.io16list.liste:
                                if io.get('addr') == addr:
                                    self.set_io16_sub(cmd,io,cmd.get('Value'))
                    for cmd in cmds:                            
                        if cmd.get('Value') == 1: #erst alle auf Null setzen
                            addr = cmd.get('UID') 
                            for io in self.io16list.liste:
                                if io.get('addr') == addr:
                                    self.set_io16_sub(cmd,io,cmd.get('Value'))    
                else:
                    cmd = cmds
                    addr = cmd.get('UID') 
                    for io in self.io16list.liste:
                        if io.get('addr') == addr:
                            self.set_io16_sub(cmd,io,cmd.get('Value'))
        return True                           

    def _set_LED_zusammen(self,LED,start,ende,red,green,blue,transitiontime):
        laenge = (ende-start)                        
        o_r, o_g, o_b = LED.get('LED').get_rgb_values(start, 1)
        steps = abs(red-o_r) + abs(green-o_g) + abs(blue-o_b)
        wartezeit = float(transitiontime) / steps 
        while o_r <> red or o_g <> green or o_b <> blue:
            while (laenge) > 16:
                laenge = 16
                if (red-o_r) > 0:
                    o_r = o_r + 1
                    LED.get('LED').set_rgb_values(start, laenge, o_r, o_g, o_b)
                    time.sleep(wartezeit)
                elif (red-o_r) < 0:
                    o_r = o_r - 1
                    LED.get('LED').set_rgb_values(start, laenge, o_r, o_g, o_b)
                    time.sleep(wartezeit)
                if (green-o_g) > 0:
                    o_g = o_g + 1
                    LED.get('LED').set_rgb_values(start, laenge, o_r, o_g, o_b)
                    time.sleep(wartezeit)
                elif (green-o_g) < 0:
                    o_g = o_g - 1
                    LED.get('LED').set_rgb_values(start, laenge, o_r, o_g, o_b)
                    time.sleep(wartezeit) 
                if (blue-o_b) > 0:
                    o_b = o_b + 1
                    LED.get('LED').set_rgb_values(start, laenge, o_r, o_g, o_b)
                    time.sleep(wartezeit)
                elif (blue-o_b) < 0:
                    o_b = o_b - 1
                    LED.get('LED').set_rgb_values(start, laenge, o_r, o_g, o_b)
                    time.sleep(wartezeit)                                     
                start += laenge
                laenge = (ende-start)
            else:
                if (red-o_r) > 0:
                    o_r = o_r + 1
                    LED.get('LED').set_rgb_values(start, laenge, o_r, o_g, o_b)
                    time.sleep(wartezeit)
                elif (red-o_r) < 0:
                    o_r = o_r - 1
                    LED.get('LED').set_rgb_values(start, laenge, o_r, o_g, o_b)
                    time.sleep(wartezeit)
                if (green-o_g) > 0:
                    o_g = o_g + 1
                    LED.get('LED').set_rgb_values(start, laenge, o_r, o_g, o_b)
                    time.sleep(wartezeit)
                elif (green-o_g) < 0:
                    o_g = o_g - 1
                    LED.get('LED').set_rgb_values(start, laenge, o_r, o_g, o_b)
                    time.sleep(wartezeit) 
                if (blue-o_b) > 0:
                    o_b = o_b + 1
                    LED.get('LED').set_rgb_values(start, laenge, o_r, o_g, o_b)
                    time.sleep(wartezeit)
                elif (blue-o_b) < 0:
                    o_b = o_b - 1
                    LED.get('LED').set_rgb_values(start, laenge, o_r, o_g, o_b)
                    time.sleep(wartezeit)       
        
    def set_LED(self, **kwargs):
#        device, rot, gruen, blau, transitiontime, transition=ANSTEIGEND
        device = kwargs.get('Device')
#        range check kwargs
        try:
            for varia in ['red','green','blue']:
                if int(kwargs.get(varia)) > 255:
                    kwargs[varia] = 255
                if int(kwargs.get(varia)) < 0:
                    kwargs[varia] = 0            
            green = int(kwargs.get('red',0))
            blue = int(kwargs.get('green',0))
            red = int(kwargs.get('blue',0))
    
            transitiontime = kwargs.get('transitiontime')
            transition = kwargs.get('transition',ANSTEIGEND)
            proc = kwargs.get('percentage',None)
    
            red_1 = kwargs.get('blue_1','None')
            green_1 = kwargs.get('red_1','None')
            blue_1 = kwargs.get('green_1','None')
    
            red_2 = int(kwargs.get('blue_2',0))
            green_2 = int(kwargs.get('red_2',0))
            blue_2 = int(kwargs.get('green_2',0))        
        except:
            print(kwargs)
            return False
#        gradient
#        lauflicht          
        LEDDict = tifo_config.LEDsOut.get(device)
        uid = LEDDict.get('UID')
        start = LEDDict.get('Start')
        ende = LEDDict.get('Ende')
#        TODO vectorize
        delta_r = 0
        delta_g = 0
        delta_b = 0        
        if str(red_1) == 'None' and str(green_1) == 'None' and str(blue_1) == 'None':
            red = [int(red)]*16
            green = [int(green)]*16
            blue = [int(blue)]*16 
            gradient = False
        else:
            laenge = (ende-start)
            if not str(red_1) == 'None':
                delta_r = int(red_1) - int(red)
                delta_pr = float(delta_r) / laenge
            else:
                delta_pr = 0
            if not str(green_1) == 'None':
                delta_g = (int(green_1) -int(green))
                delta_pg = float(delta_g) / laenge
            else:
                delta_pg = 0                
            if not str(blue_1) == 'None':
                delta_b = (int(blue_1) - int(blue))    
                delta_pb = float(delta_b) / laenge 
            else:
                delta_pb = 0 
            gradient = True

        for LED in self.LEDList.liste:
            if LED.get('addr') == uid:
                laenge = (ende-start)
                if proc <> None and 0 <= proc <= 100:
                    laenge = int(float(proc)/100 * laenge)                  
                elif proc <> None and proc < 0:
                    laenge = 0  
                if (transitiontime == None or transitiontime <= 0) and not gradient:                  
                    while (laenge) > 16:
                        laenge = 16
#                         TODO check that command is executed
#                        while not (red, green, blue) == LED.get('LED').get_rgb_values(start, laenge):
                        LED.get('LED').set_rgb_values(start, laenge, red, green, blue)
                        start += laenge
                        laenge = (ende-start)
                    else:
                        LED.get('LED').set_rgb_values(start, laenge, red, green, blue)
                elif not (transitiontime == None or transitiontime <= 0):
#                    Ansteigend
                    if transition == ANSTEIGEND:
                        wartezeit = float(transitiontime) / (ende-start)
                        for birne in range(start,ende):
                            LED.get('LED').set_rgb_values(birne, 1, red, green, blue)  
                            time.sleep(wartezeit)
                    elif transition == ABSTEIGEND:
                        wartezeit = float(transitiontime) / (ende-start)
                        for birne in list(reversed(range(start,ende))):
                            LED.get('LED').set_rgb_values(birne, 1, red, green, blue)  
                            time.sleep(wartezeit)        
                    elif transition == ZUSAMMEN:
                        self._set_LED_zusammen(LED,start,ende,red,green,blue,transitiontime)  
                else:
                    for birne in range(start,(start+laenge)):
                        LED.get('LED').set_rgb_values(birne, 1, [int(red)]*16, [int(green)]*16, [int(blue)]*16)  
                        red += delta_pr
                        green += delta_pg
                        blue += delta_pb  
                    for birne in range((start+laenge),ende):
                        LED.get('LED').set_rgb_values(birne, 1, [int(red_2)]*16, [int(green_2)]*16, [int(blue_2)]*16)                          
#        TODO Transition, 4 types
#        von links nach rechts (ansteigend), von rechts nach links (absteigend)
#        alle zusammen, beides                

        return True
         
    def set_drb(self, device, value):
        uid_cmds = tifo_config.DualRelay.get(device) 
        uid = ''
        for cmd in uid_cmds:
            if (cmd.get('Value')) == float(value):
                uid = cmd.get('UID')
                state = cmd.get('state')
                relaynr = cmd.get('relay')
        for relay in self.drb:
            temp_uid = str(relay.get_identity()[1]) +"."+ str(relay.get_identity()[0])
            if temp_uid == uid:
                relay.set_selected_state(relaynr, state)
                return True
        return False
         
         
    def set_device(self, data_ev): 
#       TODO do threaded with stop criteria
        if tifo_config.outputs.get(data_ev.get('Device')) == 'IO16o':
            return self.set_io16(data_ev.get('Device'),data_ev.get('Value'))
        elif tifo_config.outputs.get(data_ev.get('Device')) == 'IO16o':
            return self.set_io16(data_ev.get('Device'),data_ev.get('Value'))
        elif tifo_config.outputs.get(data_ev.get('Device')) == 'LEDs':
            return self.set_LED(**data_ev) #data_ev.get('Device'),data_ev.get('red'),data_ev.get('green'),data_ev.get('blue'),data_ev.get('transitiontime'))      
        elif tifo_config.outputs.get(data_ev.get('Device')) == 'DualRelay':
            return self.set_drb(data_ev.get('Device'),data_ev.get('Value'))            
        else:
            return False

    def cb_enumerate(self, 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:
                self.LEDs.append(LEDStrip(uid, self.ipcon))
                temp_uid = str(self.LEDs[-1].get_identity()[1]) +"."+ str(self.LEDs[-1].get_identity()[0])
                self.LEDList.addLED(self.LEDs[-1],temp_uid)
                self.LEDs[-1].set_frame_duration(200)
                if tifo_config.LEDs.get(temp_uid) <> None:
                    self.LEDs[-1].set_chip_type(tifo_config.LEDs.get(temp_uid)[0])
                    self.LEDs[-1].set_frame_duration(tifo_config.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:
                self.io.append(IO16(uid, self.ipcon))
                temp_uid = str(self.io[-1].get_identity()[1]) +"."+ str(self.io[-1].get_identity()[0])
                self.io16list.addIO(self.io[-1],temp_uid,16)
                self.io[-1].set_debounce_period(100)
                if tifo_config.IO16.get(temp_uid) <> None:
                    self.io[-1].set_port_interrupt('a', tifo_config.IO16.get(temp_uid)[0])
                    self.io[-1].set_port_interrupt('b', tifo_config.IO16.get(temp_uid)[1])
                    self.io[-1].set_port_configuration('a', tifo_config.IO16.get(temp_uid)[0],'i',True)
                    self.io[-1].set_port_configuration('b', tifo_config.IO16.get(temp_uid)[1],'i',True)                    
                    self.io[-1].set_port_configuration('a', tifo_config.IO16.get(temp_uid)[2],'o',False)
                    self.io[-1].set_port_configuration('b', tifo_config.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])
                    self.io[-1].register_callback(self.io[-1].CALLBACK_INTERRUPT, partial( self.cb_interrupt, device = self.io[-1], uid = temp_uid ))
                    found  = True
             
            if device_identifier == AmbientLight.DEVICE_IDENTIFIER:
                self.al.append(AmbientLight(uid, self.ipcon))
                self.al[-1].set_illuminance_callback_threshold('o', 0, 0)
                self.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 = self.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))
                
                self.al[-1].register_callback(self.al[-1].CALLBACK_ILLUMINANCE_REACHED, partial( self.cb_ambLight,  device=args))
                temp_uid = str(self.al[-1].get_identity()[1]) +"."+ str(self.al[-1].get_identity()[0])               
                found  = True  
                thread_cb_amb = Timer(60, self.thread_ambLight, [self.al[-1]])
                thread_cb_amb.start() 

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

            if device_identifier == BrickletDualRelay.DEVICE_IDENTIFIER:
                self.drb.append(BrickletDualRelay(uid, self.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:   
                self.md.append(BrickletMotionDetector(uid, self.ipcon))
                temp_uid = str(self.md[-1].get_identity()[1]) +"."+ str(self.md[-1].get_identity()[0])
                self.md[-1].register_callback(self.md[-1].CALLBACK_MOTION_DETECTED, partial( self.cb_md, device = self.md[-1], uid = temp_uid ))  
                self.md[-1].register_callback(self.md[-1].CALLBACK_DETECTION_CYCLE_ENDED, partial( self.cb_md_end, device = self.md[-1], uid = temp_uid ))
                found  = True                
            
            if device_identifier == BrickletSoundIntensity.DEVICE_IDENTIFIER:   
                self.si.append(BrickletSoundIntensity(uid, self.ipcon))
                temp_uid = str(self.si[-1].get_identity()[1]) +"."+ str(self.si[-1].get_identity()[0])
# TODO: remove all ifs
                found  = True             
                self.si[-1].set_debounce_period(1000)                
                self.si[-1].register_callback(self.si[-1].CALLBACK_INTENSITY_REACHED, partial( self.cb_si, device = self.si[-1], uid = temp_uid ))  
                self.si[-1].set_intensity_callback_threshold('>', 200, 0)                    
            
            if device_identifier == BrickletPTC.DEVICE_IDENTIFIER:
                self.ptc.append(BrickletPTC(uid, self.ipcon))
                temp_uid = str(self.ptc[-1].get_identity()[1]) +"."+ str(self.ptc[-1].get_identity()[0])
                found  = True  
                thread_pt_ = Timer(5, self.thread_pt, [self.ptc[-1]])
                thread_pt_.start()   
                self.threadliste.append(thread_pt_)
            
            if device_identifier == BrickMaster.DEVICE_IDENTIFIER:   
                self.master.append(BrickMaster(uid, self.ipcon))
                thread_rs_error = Timer(60, self.thread_RSerror, [])
                #thread_rs_error.start()       
                if tifo_config.inputs.get(uid) <> None:
                    found  = True                 
            
            if not found:
                print connected_uid, uid, device_identifier

        
    def cb_connected(self, connected_reason):
        # Enumerate devices again. If we reconnected, the Bricks/Bricklets
        # may have been offline and the configuration may be lost.
        # In this case we don't care for the reason of the connection
        self.ipcon.enumerate()     
class readTFsensors:

    def __init__(self):
        self.tmpHW = None
        self.tmpFR = None
        self.tmpMain = None
        self.tmpHWval = 0
        self.tmpFRval = 0
        self.tmpMainval = 0

        # Create IP Connection
        self.ipcon = IPConnection() 

        # Register IP Connection callbacks
        self.ipcon.register_callback(IPConnection.CALLBACK_ENUMERATE, self.cb_enumerate)
        self.ipcon.register_callback(IPConnection.CALLBACK_CONNECTED, self.cb_connected)

        # Connect to brickd, will trigger cb_connected
        self.ipcon.connect( HOST, PORT ) 

        self.ipcon.enumerate()
        
        # wait until all values are being received
        Logger.debug('waiting for all sensors to send values ...')
        while self.tmpHWval==0 or self.tmpFRval==0 or self.tmpMainval==0:
            now = round( datetime.datetime.timestamp(datetime.datetime.now()) ) 
            Logger.debug( str(now) + ' (HW, FR, main) ' + str(self.tmpHWval)+', '+str(self.tmpFRval)+', '+str(self.tmpMainval) )
            time.sleep(15)               # wait 15 seconds
        Logger.debug( 'all sensors found: (HW, FR, main)' + str(self.tmpHWval)+', '+str(self.tmpFRval)+', '+str(self.tmpMainval) )    
        
        # loop to check if source code was changed, 
        # then exit the python program in order to get it restarted by the shell script
        while True:
            time.sleep(120)               # wait 2 minutes
            # check if script source code has changed
            newScrChgDate = os.path.getmtime(__file__)
            if ( scriptChangeDate != newScrChgDate ):
                Logger.info("Source code changed, (ending script). Old: "+str(scriptChangeDate) + ", New: " + str(newScrChgDate) )
                sys.exit(9)  # means 'reload and restart'
                
            # check if debugging is requested
            if os.path.isfile('debug_off'):
                Logger.setLevel(logging.INFO) 
                
            # check if debugging is requested
            if os.path.isfile('debug_on'):
                Logger.setLevel(logging.DEBUG) 
                
        
    # Callback updates temperature 
    # - for heatwater temperature
    def cb_tempHW(self, temperature):   
        self.tmpHWval = temperature/100.0
        writeSensFile("HW", self.tmpHWval, self.tmpHWval, self.tmpFRval, self.tmpMainval)
    # - for front room temperature
    def cb_tempFR( self, temperature):
        self.tmpFRval  = temperature/100.0
        writeSensFile("FR", self.tmpFRval, self.tmpHWval, self.tmpFRval, self.tmpMainval)
    # - for main room temperature
    def cb_tempMain(self, temperature):
        self.tmpMainval = temperature/100.0
        writeSensFile("Main", self.tmpMainval, self.tmpHWval, self.tmpFRval, self.tmpMainval)


    # Callback handles device connections and configures possibly lost 
    # configuration of lcd and temperature callbacks, backlight etc.
    def cb_enumerate(self, uid, connected_uid, position, hardware_version, firmware_version, device_identifier, enumeration_type):
        if enumeration_type == IPConnection.ENUMERATION_TYPE_CONNECTED or \
           enumeration_type == IPConnection.ENUMERATION_TYPE_AVAILABLE:
                
            # Enumeration is for Temperature Bricklets
            if device_identifier == Temperature.DEVICE_IDENTIFIER:
                # Create individual temperature device objects for each sensor
                if uid==HW_ID:
                    self.tmpHW = Temperature(uid, self.ipcon) 
                    self.tmpHWval = self.tmpHW.get_temperature()/100.0    # read initial value
                    writeSensFile("HW", self.tmpHWval, self.tmpHWval, self.tmpFRval, self.tmpMainval)
                    self.tmpHW.register_callback( self.tmpHW.CALLBACK_TEMPERATURE, self.cb_tempHW )
                    self.tmpHW.set_temperature_callback_period(500)
                elif uid==FR_ID:
                    self.tmpFR = Temperature(uid, self.ipcon) 
                    self.tmpFRval = self.tmpFR.get_temperature()/100.0    # read initial value
                    writeSensFile("FR", self.tmpFRval, self.tmpHWval, self.tmpFRval, self.tmpMainval)
                    self.tmpFR.register_callback( self.tmpFR.CALLBACK_TEMPERATURE, self.cb_tempFR )
                    self.tmpFR.set_temperature_callback_period(500)
                elif uid==MAIN_ID:
                    self.tmpMain = Temperature(uid, self.ipcon) 
                    self.tmpMainval = self.tmpMain.get_temperature()/100.0    # read initial value
                    writeSensFile("Main", self.tmpMainval, self.tmpHWval, self.tmpFRval, self.tmpMainval)
                    self.tmpMain.register_callback( self.tmpMain.CALLBACK_TEMPERATURE, self.cb_tempMain )
                    self.tmpMain.set_temperature_callback_period(500)

    # Callback handles reconnection of IP Connection
    def cb_connected(self, connected_reason):
        # Enumerate devices again. If we reconnected, the Bricks/Bricklets
        # may have been offline and the configuration may be lost.
        # In this case we don't care for the reason of the connection
        self.ipcon.enumerate()
from tinkerforge.bricklet_piezo_speaker import PiezoSpeaker

if __name__ == "__main__":
    try:
        host = sys.argv[1]
        port = int(sys.argv[2])
        uid = sys.argv[3]
        frequency = int(sys.argv[4])
        trigger = int(sys.argv[5])
        wait = int(sys.argv[6])
    except:
        print("usage: {0} <host> <port> <ps-uid> <frequency> <trigger-duration> <wait-duration>".format(sys.argv[0]))
        sys.exit(1)

    ipcon = IPConnection()
    ps = PiezoSpeaker(uid, ipcon)
    sema = Semaphore(0)

    ipcon.connect(host, port)

    def beep_finished():
        sema.release()

    ps.register_callback(ps.CALLBACK_BEEP_FINISHED, beep_finished)
    ps.beep(trigger, frequency)

    sema.acquire()
    sleep(wait / 1000.0)

    ipcon.disconnect()
Exemple #57
0
class Blinkenlights(QApplication):
    HOST = "localhost"
    PORT = 4223

    ipcon = None

    projects = []
    active_project = None

    error_msg = None

    def __init__(self, args):
        super(QApplication, self).__init__(args)

        self.error_msg = QErrorMessage()
        self.error_msg.setWindowTitle("Starter Kit: Blinkenlights Demo " + config.DEMO_VERSION)

        signal.signal(signal.SIGINT, self.exit_demo)
        signal.signal(signal.SIGTERM, self.exit_demo)

        self.make_gui()
        self.connect()

    def exit_demo(self, signl=None, frme=None):
        try:
            self.ipcon.disconnect()
            self.timer.stop()
            self.tabs.destroy()
        except:
            pass

        sys.exit()

    def make_gui(self):
        self.main = MainWindow(self)
        self.main.setWindowIcon(QIcon(os.path.join(ProgramPath.program_path(), "demo-icon.png")))

        self.tabs = QTabWidget()

        widget = QWidget()
        layout = QVBoxLayout()
        layout.addWidget(self.tabs)
        widget.setLayout(layout)

        self.main.setCentralWidget(widget)

        self.setup = SetupWidget(self.tabs, self)
        self.tetris = TetrisWidget(self.tabs, self)
        self.pong = PongWidget(self.tabs, self)
        self.fire = FireWidget(self.tabs, self)
        self.text = TextWidget(self.tabs, self)
        self.images = ImagesWidget(self.tabs, self)
        self.rainbow = RainbowWidget(self.tabs, self)

        self.projects.append(self.setup)
        self.projects.append(self.tetris)
        self.projects.append(self.pong)
        self.projects.append(self.fire)
        self.projects.append(self.text)
        self.projects.append(self.images)
        self.projects.append(self.rainbow)

        self.tabs.addTab(self.setup, "Setup")
        self.tabs.addTab(self.tetris, "Tetris")
        self.tabs.addTab(self.pong, "Pong")
        self.tabs.addTab(self.fire, "Fire")
        self.tabs.addTab(self.text, "Text")
        self.tabs.addTab(self.images, "Images")
        self.tabs.addTab(self.rainbow, "Rainbow")

        self.active_project = self.projects[0]

        self.tabs.currentChanged.connect(self.tab_changed_slot)

        self.main.setWindowTitle("Starter Kit: Blinkenlights Demo " + config.DEMO_VERSION)
        self.main.show()

    def connect(self):
        config.UID_LED_STRIP_BRICKLET = None
        self.setup.label_led_strip_found.setText('No')
        self.setup.label_led_strip_uid.setText('None')

        config.UID_MULTI_TOUCH_BRICKLET = None
        self.setup.label_multi_touch_found.setText('No')
        self.setup.label_multi_touch_uid.setText('None')

        config.UID_DUAL_BUTTON_BRICKLET = (None, None)
        self.setup.label_dual_button1_found.setText('No')
        self.setup.label_dual_button1_uid.setText('None')
        self.setup.label_dual_button2_found.setText('No')
        self.setup.label_dual_button2_uid.setText('None')

        config.UID_PIEZO_SPEAKER_BRICKLET = None
        self.setup.label_piezo_speaker_found.setText('No')
        self.setup.label_piezo_speaker_uid.setText('None')

        config.UID_SEGMENT_DISPLAY_4X7_BRICKLET = None
        self.setup.label_segment_display_found.setText('No')
        self.setup.label_segment_display_uid.setText('None')

        if self.ipcon != None:
            try:
                self.ipcon.disconnect()
            except:
                pass

        self.ipcon = IPConnection()

        host = self.setup.edit_host.text()
        port = self.setup.spinbox_port.value()
        try:
            self.ipcon.connect(host, port)
        except Error as e:
            self.error_msg.showMessage('Connection Error: ' + str(e.description) + "<br><br>Brickd installed and running?")
            return
        except socket.error as e:
            self.error_msg.showMessage('Socket error: ' + str(e) + "<br><br>Brickd installed and running?")
            return

        self.ipcon.register_callback(IPConnection.CALLBACK_ENUMERATE,
                                     self.cb_enumerate)
        self.ipcon.register_callback(IPConnection.CALLBACK_CONNECTED,
                                     self.cb_connected)

        # Wait for a second to give user visual feedback
        timer = QTimer(self)
        timer.setSingleShot(True)
        timer.timeout.connect(self.ipcon.enumerate)
        timer.start(250)

    def tab_changed_slot(self, tabIndex):
        self.active_project.stop()
        self.active_project = self.projects[tabIndex]
        self.active_project.start()

    def cb_enumerate(self, uid, connected_uid, position, hardware_version,
                     firmware_version, device_identifier, enumeration_type):
        if enumeration_type == IPConnection.ENUMERATION_TYPE_CONNECTED or \
           enumeration_type == IPConnection.ENUMERATION_TYPE_AVAILABLE:
            if device_identifier == LEDStrip.DEVICE_IDENTIFIER:
                config.UID_LED_STRIP_BRICKLET = uid
                self.setup.label_led_strip_found.setText('Yes')
                self.setup.label_led_strip_uid.setText(uid)
            elif device_identifier == MultiTouch.DEVICE_IDENTIFIER:
                config.UID_MULTI_TOUCH_BRICKLET = uid
                self.setup.label_multi_touch_found.setText('Yes')
                self.setup.label_multi_touch_uid.setText(uid)
            elif device_identifier == DualButton.DEVICE_IDENTIFIER:
                if config.UID_DUAL_BUTTON_BRICKLET[0] == None:
                    config.UID_DUAL_BUTTON_BRICKLET = (uid, None)
                    self.setup.label_dual_button1_found.setText('Yes')
                    self.setup.label_dual_button1_uid.setText(uid)
                else:
                    config.UID_DUAL_BUTTON_BRICKLET = (config.UID_DUAL_BUTTON_BRICKLET[0], uid)
                    self.setup.label_dual_button2_found.setText('Yes')
                    self.setup.label_dual_button2_uid.setText(uid)
            elif device_identifier == PiezoSpeaker.DEVICE_IDENTIFIER:
                config.UID_PIEZO_SPEAKER_BRICKLET = uid
                self.setup.label_piezo_speaker_found.setText('Yes')
                self.setup.label_piezo_speaker_uid.setText(uid)
            elif device_identifier == SegmentDisplay4x7.DEVICE_IDENTIFIER:
                config.UID_SEGMENT_DISPLAY_4X7_BRICKLET = uid
                self.setup.label_segment_display_found.setText('Yes')
                self.setup.label_segment_display_uid.setText(uid)

    def cb_connected(self, connected_reason):
        if connected_reason == IPConnection.CONNECT_REASON_AUTO_RECONNECT:
            while True:
                try:
                    self.ipcon.enumerate()
                    break
                except Error as e:
                    self.error_msg.showMessage('Enumerate Error: ' + str(e.description))
                    time.sleep(1)