Пример #1
0
class PhoneControls:
    def __init__(self,
                 callbPush,
                 callbHang,
                 ledPins=(17, 27, 22),
                 buzzerPin=13,
                 pttPin=18,
                 canPin=19):
        # define properties
        self.led = RGBLED(ledPins[0], ledPins[1], ledPins[2])
        self.buzzer = Buzzer(buzzerPin, active_high=True)
        self.pttButton = Device.pin_factory.pin(pttPin)
        self.canButton: Pin = Device.pin_factory.pin(canPin)
        # configure hardware
        self.__configPinHandler__(self.pttButton, self.__pttCallback__)
        self.__configPinHandler__(self.canButton, self.__canCallback__)
        self.cbCan = callbHang
        self.cbPtt = callbPush

    def __configPinHandler__(self, button: Pin, cb):
        button.edges = "both"
        button.input_with_pull("up")
        button.bounce = .250
        button.when_changed = cb

    def __canCallback__(self, ticks, state):
        sleep(0.2)
        state = self.canButton.state
        log.debug("Can button state=%d", state)
        if state == 0:
            self.cbCan(CanState.HUNGUP)
        else:
            self.cbCan(CanState.LIFTED)

    def __pttCallback__(self, ticks, state):
        sleep(0.2)
        state = self.pttButton.state
        log.debug("PTT button state=%d", state)
        if state == 1:
            self.cbPtt(PttState.RELEASED)
        else:
            self.cbPtt(PttState.PRESSED)

    def ledOff(self):
        self.led.off()

    def ledOn(self, rgb=(1, 1, 1)):
        self.led.value = rgb

    def startBlinking(self, rgb=(1, 1, 1), off_time=0.5, on_time=0.5):
        self.led.blink(on_time=on_time,
                       off_time=off_time,
                       on_color=rgb,
                       background=True)

    def beep(self):
        self.buzzer.beep(on_time=1, off_time=0.25, background=True)

    def stopBeep(self):
        self.buzzer.off()
Пример #2
0
def run():
    global R
    global G
    global B
    led = RGBLED(4, 17, 27)
    ldr = LightSensor(22, 50)

    R = (1, 0, 0)
    G = (0, 1, 0)
    B = (0, 0, 1)
    N = (0, 0, 0)
    Y = (1, 1, 0)
    #  W = (1,1,1)
    #  M = (1,0,1)

    night_time
    on_time = 0.01
    on_time_noacft = 0.20

    server_address = ('localhost', 30003)
    BUFF_LEN = 256
    connCnt = 0

    x = threading.Thread(target=thread_function, args=(1, ldr))
    x.start()

    # INIT LED - Blink BLUE while not connected & data
    led.blink(0.25, 0.25, 0, 0, B, N)

    connect(server_address, ldr)
    try:
        while (1):
            data = sock.recv(BUFF_LEN)
            if (len(data) > 10):
                led.blink(on_time, 0, 0, 0, G, N, 1)
            else:
                led.blink(on_time, 0, 0, 0, R, N, 1)

            if not data:
                led.color = R
                connCnt = connCnt + 1
                if (connCnt > 10):
                    l('Error. Try to reconnect .... ')
                    close()
                    # No blink thread = block script for 20sec = time to SDR recovery
                    led.blink(1, 1, 0, 0, Y, N, 10, False)
                    led.blink(0.25, 0.25, 0, 0, B, N)
                    connect(server_address, ldr)
            else:
                connCnt = 0

    finally:
        led.color = N
        close()
Пример #3
0
def get_rgbled(verbose=True):
    """Tries to get gpiozero RGBLED object at pins PIN_R|G|B if WITH_RGBLED in config file"""
    led = None
    if WITH_RGBLED:
        try:
            from gpiozero import RGBLED
            from gpiozero.pins.rpigpio import RPiGPIOPin

            led = RGBLED(RPiGPIOPin(PIN_R), RPiGPIOPin(PIN_G), RPiGPIOPin(PIN_B), active_high=True)
            led.blink(.25, .25, on_color=(1, 1, 1), n=5)
        except (OSError, RuntimeError, ImportError) as e:
            log('** Not using RGBLED with GPIOZERO ({} [{}]). Check your "{}" file.'
                .format(e, e.__class__, CONFIG_FILENAME), 'warn', verbose)
    return led
Пример #4
0
def get_rgbled(verbose=True):
    """Tries to get gpiozero RGBLED object at pins PIN_R|G|B if WITH_RGBLED in config file"""
    led = None
    if WITH_RGBLED:
        try:
            from gpiozero import RGBLED
            from gpiozero.pins.rpigpio import RPiGPIOPin

            led = RGBLED(RPiGPIOPin(PIN_R),
                         RPiGPIOPin(PIN_G),
                         RPiGPIOPin(PIN_B),
                         active_high=True)
            led.blink(.25, .25, on_color=(1, 1, 1), n=5)
        except (OSError, RuntimeError, ImportError) as e:
            log(
                '** Not using RGBLED with GPIOZERO ({} [{}]). Check your "{}" file.'
                .format(e, e.__class__, CONFIG_FILENAME), 'warn', verbose)
    return led
Пример #5
0
class PyDensha:
    def __init__(self, led_pins=None):
        self._led = None

        self.assign_led(led_pins)

    @_ignore_exception
    def assign_led(self, led_pins):
        self._close_led()

        try:
            self._led = RGBLED(red=led_pins.get('red'),
                               green=led_pins.get('green'),
                               blue=led_pins.get('blue'))
        except PinInvalidPin:
            pass

    @_ignore_exception
    def _close_led(self):
        self._led.close()

    @_ignore_exception
    def operate_led(self, train_infos, on_time=1, off_time=1):
        def _are_all_trains_operate_normally(train_infos):
            return all(train_info == '平常運転' for train_info in train_infos)

        def _is_all_train_either_operate_normally_or_delayed(train_infos):
            return all(train_info == '平常運転' or train_info == '遅延'
                       for train_info in train_infos)

        if None not in train_infos:
            if _are_all_trains_operate_normally(train_infos):
                self._led.color = Color('green')
            elif _is_all_train_either_operate_normally_or_delayed(train_infos):
                self._led.blink(on_time=on_time,
                                off_time=off_time,
                                on_color=Color('yellow'))
            else:
                self._led.blink(on_time=on_time,
                                off_time=off_time,
                                on_color=Color('red'))
Пример #6
0
class Led(object):
    # Takes in an initial color and the pin numbers of the RGB LED
    def __init__(self, color, pins):
        # Unpack the pin values
        r_pin, g_pin, b_pin = pins
        # Init the RGB LED object, we will be using pwm and the color pins of
        # out LED are set to LOW
        self.led = RGBLED(r_pin, g_pin, b_pin, active_high=True, pwm=True)
        self.setColor(color)

    # Set the color of the LED
    def setColor(self, color: Color):
        print("Setting color to:", color.getLEDColor())
        self.led.color = color.getLEDColor()

    def blink(self):
        print("Led is turning on and off.")
        self.led.blink()
        pass

    def fade(self, colors):
        # TODO: Fade through the list of colors
        pass

    def toggleOn(self):
        # Turn on/off the led
        pass


############ Example usage of the class ############
# Green
# init_color = Color(0, 255, 0)
# pins = (16, 20, 21)

# # Init the class
# my_led = Led(init_color, pins)

# # Red
# red_color = Color(255, 0, 0)
# my_led.setColor(red_color)
Пример #7
0
def Init():
    global STATUS_LED, CAMERA, BKG_FRAME, CHANNEL, STUB, MY_ADDR, USER_ID, BIN_ID, CONNECTION_FLAG, ID_DIRC, REGIS_FLAG, MPU

    if os.path.exists('ID.json'):
        ID_DIRC = json.load(open('ID.json'))
        USER_ID = ID_DIRC['USER_ID']
        BIN_ID = ID_DIRC['BIN_ID']
        REGIS_FLAG = True
    else:
        json.dump(ID_DIRC, open('ID.json', 'w'))

    STATUS_LED = RGBLED(red=16, green=20, blue=21)
    STATUS_LED.blink(0.1, 0.1, on_color=(1, 0.6, 0))  # 闪灯

    # 首先连接相机
    CAMERA = PiCamera()
    CAMERA.resolution = (640, 480)
    if CAMERA is None:
        raise SystemExit('摄像头连接失败')
    # 摄像头预热
    time.sleep(5)

    # 获得一个稳定的背景
    BKG_FRAME = GetBackGround()

    # 初始化连接状态
    CHANNEL = grpc.insecure_channel(SERVER_ADDR)
    STUB = waste_pb2_grpc.WasteServiceStub(CHANNEL)
    MY_ADDR = get_host_ip()
    log.info('当前IP地址为: {}'.format(MY_ADDR))
    # 启动反向服务
    StartSever()

    # 初始化完成
    log.info('初始化完成')
    # 最后注册垃圾桶
    Register()
Пример #8
0
class AlertHarness:
    def __init__(self, args):
        if args.test or args.replay:
            self.radio = None
        else:
            r = self.radio = rf95.RF95(cs=RF95_SPI_CS, int_pin=RF95_IRQ_PIN, reset_pin=RF95_RESET_PIN)
            assert r.init(), "failed to intialize radio"
            r.set_modem_config(rf95.Bw125Cr45Sf128)
            r.set_frequency(RF95_FREQ)

        self._args = args

        self.log_handle = open(args.log, 'w') if args.log else None
        self.replay_handle = open(args.replay, 'r') if args.replay else None
        self._pending_line = None
        self._time_offset = 0

        if self.replay_handle:
            if self.read_replay_line():
                self._time_offset = time.time() - self._pending_line[0]

        self.test = args.test
        self.use_tts = args.tts
        self.use_alarm = args.alarm
        self.numbers = args.phone
        self.emails = args.email

        self.stopping = False
        self.led = RGBLED(*RGBLED_PINS)

        self.lcd_thread = LCDThread(SEGMENT_PINS, DIGIT_PINS)

        self.trouble_tags = set()
        self.known_tags = set()

        self.monitor_thread = BackgroundThread(self.status_loop, start=False)
        self.announce_thread = None
        self._buzzer = False

        if twilio is not None:
            self.twilio_client = TwilioClient(TWILIO_SID, TWILIO_AUTH)
        else:
            self.twilio_client = None

        if sendgrid is not None:
            self.mail_client = sendgrid.SendGridAPIClient(apikey=SENDGRID_API_KEY)
        else:
            self.mail_client = None

        self.conn = None
        self.states = StateTracker()

    def read_replay_line(self) -> bool:
        try:
            line = next(self.replay_handle)
            ts, rssi, pkt_hex = line.split(",")
            ts = float(ts.strip())
            rssi = float(rssi.strip())
            pkt = bytes.fromhex(pkt_hex.strip())
            self._pending_line = ts, rssi, pkt
            return True
        except (StopIteration, ValueError):
            self._pending_line = None
            return False

    def set_plotter(self, address: str, port: int = PLT_DEFAULT_PORT):
        if isinstance(port, str):
            port = int(port)
        elif port is None:
            port = PLT_DEFAULT_PORT

        self.conn = mpClient((address, port))

    def send_sms(self, body: str):
        if self.twilio_client is None or not self.numbers:
            return False

        ret = []
        for number in self.numbers:
            msg = self.twilio_client.messages.create(to=number, from_=TWILIO_NUMBER, body=body)
            ret.append(msg)

        return ret

    def send_email(self, subject: str, body: str):
        if self.mail_client is None or not self.emails:
            return False

        personalization = Personalization()

        for email in self.emails:
            email = Email(email)
            personalization.add_to(email)

        from_email = Email(SENDGRID_FROM_ADDRESS)
        content = Content("text/plain", body)
        mail = Mail(from_email, subject, None, content)
        mail.add_personalization(personalization)
        return self.mail_client.client.mail.send.post(request_body=mail.get())

    def get_packet(self, timeout=None) -> Optional[RadioPacket]:
        packet = None

        if self.test:
            return
        elif self.replay_handle:
            packet = self.replay_packet(timeout)
        elif self.radio:
            start = time.time()

            while not self.radio.available():
                sleep(0.005)
                if timeout and (time.time() - start > timeout):
                    return

            rxbuf = self.radio.recv()
            rxbuf = bytes(rxbuf[4:])  # skip flag
            rssi = self.radio.last_rssi

            try:
                packet = RadioPacket.from_bytes(rxbuf, rssi, timestamp=time.time())
            except Exception as e:
                h = rxbuf.hex()
                hexstr = ' '.join(h[x:x + 2] for x in range(0, len(h), 2))
                new_e = RuntimeError("error parsing packet with length %d and data:\n%s"
                                     % (len(rxbuf), hexstr))
                raise new_e from e

        if packet:
            self.states.update(packet)
            return packet

    def replay_packet(self, timeout=None):
        if self._pending_line:
            target = self._pending_line[0] + self._time_offset
            sleep_for = target - time.time()

            if timeout and sleep_for > timeout:
                sleep(timeout)
                return None
            else:
                sleep(max(0, sleep_for))
                timestamp, rssi, rxbuf = self._pending_line
                timestamp = target

                if not self.read_replay_line():
                    print("end of log, stopping")
                    self.stopping = True

                return RadioPacket.from_bytes(rxbuf, rssi, timestamp=timestamp)

    def run_test(self):
        print("Test mode: will simulate an alert in 10 seconds")
        sleep(10)
        self.show_alert(42)
        print("Test mode: returning to normal in 10 seconds")
        sleep(10)
        self.clear_alert()
        print("Test mode: will exit in 5 seconds")
        sleep(5)

    def run(self):
        # Initialize everything as OK
        self.clear_alert()
        self.monitor_thread.start()
        self.lcd_thread.start()

        if self.test:
            return self.run_test()

        while not self.stopping:
            try:
                packet = self.get_packet(timeout=1)

                if not packet:
                    continue

                if self.conn:
                    self.conn.send((packet.raw, packet.rssi, packet.timestamp))

                if self.log_handle:
                    line = '%s,%s,%s' % (packet.timestamp, packet.rssi, packet.raw.hex())
                    self.log_handle.write(line + '\n')

                # print(packet.serial, packet.seq, packet.orientation, packet.rssi, packet.vbatt)
                # pprint(packet.samples[-1])

                self.known_tags.add(packet.tag)

                if self.states.state_for(packet.tag) is State.DISTRESS:
                    if packet.tag not in self.trouble_tags:
                        self.trouble_tags.add(packet.tag)
                        self.show_alert(packet.tag)
                elif packet.tag in self.trouble_tags:
                    self.trouble_tags.remove(packet.tag)
                    self.clear_alert()

            except Exception:
                traceback.print_exc()

    def status_loop(self):
        while not self.stopping:
            for i in range(int(ACTIVE_SLEEP / 0.01)):
                sleep(0.01)

                if self.stopping:
                    break

            tag_strs = ['%d: %s' % (t, self.states.state_for(t).name.lower())
                        for t in self.known_tags]
            print("Active tags:\n%s" % ('\n'.join(tag_strs) or '(none)'))

    def show_alert(self, tag: int):
        print("showing alert for tag", tag)
        self.lcd_thread.set_value(tag)
        self.led.pulse(on_color=RED)

        msg = "Tag %s is in distress!" % tag
        self.announce_msg = msg
        self.announce()

        self.send_email("Bovine Intervention alert", msg)
        self.send_sms("Bovine Intervention alert: " + msg)

    def clear_alert(self):
        print("clearing alert")
        self.led.blink(on_color=GREEN, on_time=0.05, off_time=5 - 0.05)
        self.lcd_thread.clear()
        self.announce_msg = None

        if self.announce_thread:
            self.announce_thread.stop()  # block

    def announce_cb(self, result):
        if self.announce_msg is None or self.stopping:
            # reset to None
            self.announce_thread = None
            self._buzzer = False
        elif self._buzzer:
            self._buzzer = False
            self.announce_thread = CommandThread([TTS_SCRIPT, self.announce_msg], self.announce_cb)
        else:
            self._buzzer = True
            self.announce_thread = CommandThread(["mplayer", "-really-quiet", ALARM_SOUND], self.announce_cb)

    def announce(self):
        if self.announce_thread:
            self.announce_thread.join()  # block

        self.announce_thread = CommandThread(["mplayer", ALARM_SOUND], self.announce_cb)
        self._buzzer = True

    def shutdown(self):
        self.stopping = True
        self.lcd_thread.stop()
        self.monitor_thread.join()
        self.led.close()
        #GPIO.cleanup()

        if self.announce_thread:
            self.announce_thread.stop()

        if self.radio:
            self.radio.cleanup()

        if self.log_handle:
            self.log_handle.close()

        if self.replay_handle:
            self.replay_handle.close()
Пример #9
0
import time
from gpiozero import RGBLED
from colorzero import Color

led = RGBLED(26, 6, 5, active_high=True, initial_value=Color(130, 200, 40))
blinking = False

while 1:
    command = input(" -> ")

    if command == 'on':
        led.on()
    elif command == 'off':
        led.off()
    elif command == 'blink':
        if not blinking:
            blinking = True
            led.blink(fade_in_time=0.5, fade_out_time=0.3)
        else:
            blinking = False
            led.off()
    elif command == 'quit':
        led.off()
        exit()
Пример #10
0
class ledControl(threading.Thread):
    def __init__(self):
        threading.Thread.__init__(self)
        self.color = '000000'
        self.red = 0
        self.green = 0
        self.blue = 0

        self.bRed = 0.4
        self.bGreen = 0
        self.bBlue = 0

        self.on = True
        self.blink = False
        self.RGB = RGBLED(22,23,24,False,(self.bRed, self.bGreen, self.bBlue))
    def convertColor(self):
        try:
            divider     = 256
            red         = float(int("0x"+self.color[0:2], 0))
            # red         = red-(red/2)

            green       = float(int("0x"+self.color[2:4], 0))
            green       = green-(green/2.5)

            blue        = float(int("0x"+self.color[4:6], 0))
            # blue        = blue-(blue/2)
            if red>=divider:
               red=divider
            if green>=divider:
               green=divider
            if blue>=divider:
               blue=divider
            self.red = red/divider
            self.green = green/divider
            self.blue = blue/divider
            return True
        except ValueError:
            return False
    def setColor(self, red, green, blue):
        self.RGB.color = (red,green,blue)
    def setHexColor(self, color):
        self.color = cleanColor(color)
        return self.convertColor()
    def loadAndSetColor(self, color):
        self.color = cleanColor(color)
        self.convertColor()
        self.setColor(self.red, self.green, self.blue)
        return
    def blinkLeds(self, interval, fadeTime, blinks, on):
        if not self.blink:
            Thread(target=self.blinkingThread, args=(interval,fadeTime,blinks,on, )).start()
            return True
        return False
    def blinkingThread(self, interval, fadeTime, blinks, on):
        fInterval = float(interval)
        fFadeTime = float(fadeTime)
        fBlinks = int(blinks)
        if not self.blink:
            self.blink = True
            blinker = self.RGB.blink(fInterval, fInterval, fFadeTime, fFadeTime, (self.red, self.green, self.blue), (self.bRed, self.bGreen, self.bBlue), fBlinks, False)
            self.blink = False
            blinker = None
        if on:
            self.setColor(self.red,self.green,self.blue)
        else:
            self.setColor(self.bRed, self.bGreen, self.bBlue)
    def rainbow(self):
        self.loadAndSetColor('#000000')
        time.sleep(0.5)
        self.loadAndSetColor('#110000')
        time.sleep(0.05)
        self.loadAndSetColor('#220000')
        time.sleep(0.05)
        self.loadAndSetColor('#330000')
        time.sleep(0.05)
        self.loadAndSetColor('#440000')
        time.sleep(0.05)
        self.loadAndSetColor('#550000')
        time.sleep(0.05)
        self.loadAndSetColor('#660000')
        time.sleep(0.05)
        self.loadAndSetColor('#770000')
        time.sleep(0.05)
        self.loadAndSetColor('#880000')
        time.sleep(0.05)
        self.loadAndSetColor('#990000')
        time.sleep(0.05)
        self.loadAndSetColor('#AA0000')
        time.sleep(0.05)
        self.loadAndSetColor('#BB0000')
        time.sleep(0.05)
        self.loadAndSetColor('#CC0000')
        time.sleep(0.05)
        self.loadAndSetColor('#DD0000')
        time.sleep(0.05)
        self.loadAndSetColor('#EE0000')
        time.sleep(0.05)
        self.loadAndSetColor('#FF0000')
        time.sleep(0.05)
        self.loadAndSetColor('#FF1100')
        time.sleep(0.05)
        self.loadAndSetColor('#FF2200')
        time.sleep(0.05)
        self.loadAndSetColor('#FF3300')
        time.sleep(0.05)
        self.loadAndSetColor('#FF4400')
        time.sleep(0.05)
        self.loadAndSetColor('#FF5500')
        time.sleep(0.05)
        self.loadAndSetColor('#FF6600')
        time.sleep(0.05)
        self.loadAndSetColor('#FF7700')
        time.sleep(0.05)
        self.loadAndSetColor('#FF8800')
        time.sleep(0.05)
        self.loadAndSetColor('#FF9900')
        time.sleep(0.05)
        self.loadAndSetColor('#FFAA00')
        time.sleep(0.05)
        self.loadAndSetColor('#FFBB00')
        time.sleep(0.05)
        self.loadAndSetColor('#FFCC00')
        time.sleep(0.05)
        self.loadAndSetColor('#FFDD00')
        time.sleep(0.05)
        self.loadAndSetColor('#FFEE00')
        time.sleep(0.05)
        self.loadAndSetColor('#FFFF00')
        time.sleep(0.05)
        self.loadAndSetColor('#EEFF00')
        time.sleep(0.05)
        self.loadAndSetColor('#DDFF00')
        time.sleep(0.05)
        self.loadAndSetColor('#CCFF00')
        time.sleep(0.05)
        self.loadAndSetColor('#BBFF00')
        time.sleep(0.05)
        self.loadAndSetColor('#AAFF00')
        time.sleep(0.05)
        self.loadAndSetColor('#AAFF00')
        time.sleep(0.05)
        self.loadAndSetColor('#99FF00')
        time.sleep(0.05)
        self.loadAndSetColor('#88FF00')
        time.sleep(0.05)
        self.loadAndSetColor('#77FF00')
        time.sleep(0.05)
        self.loadAndSetColor('#66FF00')
        time.sleep(0.05)
        self.loadAndSetColor('#55FF00')
        time.sleep(0.05)
        self.loadAndSetColor('#44FF00')
        time.sleep(0.05)
        self.loadAndSetColor('#33FF00')
        time.sleep(0.05)
        self.loadAndSetColor('#22FF00')
        time.sleep(0.05)
        self.loadAndSetColor('#11FF00')
        time.sleep(0.05)
        self.loadAndSetColor('#00FF00')
        time.sleep(0.05)
        self.loadAndSetColor('#00FF11')
        time.sleep(0.05)
        self.loadAndSetColor('#00FF22')
        time.sleep(0.05)
        self.loadAndSetColor('#00FF33')
        time.sleep(0.05)
        self.loadAndSetColor('#00FF44')
        time.sleep(0.05)
        self.loadAndSetColor('#00FF55')
        time.sleep(0.05)
        self.loadAndSetColor('#00FF66')
        time.sleep(0.05)
        self.loadAndSetColor('#00FF77')
        time.sleep(0.05)
        self.loadAndSetColor('#00FF88')
        time.sleep(0.05)
        self.loadAndSetColor('#00FF99')
        time.sleep(0.05)
        self.loadAndSetColor('#00FFAA')
        time.sleep(0.05)
        self.loadAndSetColor('#00FFBB')
        time.sleep(0.05)
        self.loadAndSetColor('#00FFCC')
        time.sleep(0.05)
        self.loadAndSetColor('#00FFEE')
        time.sleep(0.05)
        self.loadAndSetColor('#00FFFF')
        time.sleep(0.05)
        self.loadAndSetColor('#00EEFF')
        time.sleep(0.05)
        self.loadAndSetColor('#00DDFF')
        time.sleep(0.05)
        self.loadAndSetColor('#00CCFF')
        time.sleep(0.05)
        self.loadAndSetColor('#00BBFF')
        time.sleep(0.05)
        self.loadAndSetColor('#00AAFF')
        time.sleep(0.05)
        self.loadAndSetColor('#0099FF')
        time.sleep(0.05)
        self.loadAndSetColor('#0088FF')
        time.sleep(0.05)
        self.loadAndSetColor('#0077FF')
        time.sleep(0.05)
        self.loadAndSetColor('#0066FF')
        time.sleep(0.05)
        self.loadAndSetColor('#0055FF')
        time.sleep(0.05)
        self.loadAndSetColor('#0044FF')
        time.sleep(0.05)
        self.loadAndSetColor('#0033FF')
        time.sleep(0.05)
        self.loadAndSetColor('#0022FF')
        time.sleep(0.05)
        self.loadAndSetColor('#0011FF')
        time.sleep(0.05)
        self.loadAndSetColor('#0000FF')
        time.sleep(0.05)
        self.loadAndSetColor('#1100FF')
        time.sleep(0.05)
        self.loadAndSetColor('#2200FF')
        time.sleep(0.05)
        self.loadAndSetColor('#3300FF')
        time.sleep(0.05)
        self.loadAndSetColor('#4400FF')
        time.sleep(0.05)
        self.loadAndSetColor('#5500FF')
        time.sleep(0.05)
        self.loadAndSetColor('#6600FF')
        time.sleep(0.05)
        self.loadAndSetColor('#7700FF')
        time.sleep(0.05)
        self.loadAndSetColor('#8800FF')
        time.sleep(0.05)
        self.loadAndSetColor('#9900FF')
        time.sleep(0.05)
        self.loadAndSetColor('#AA00FF')
        time.sleep(0.05)
        self.loadAndSetColor('#BB00FF')
        time.sleep(0.05)
        self.loadAndSetColor('#CC00FF')
        time.sleep(0.05)
        self.loadAndSetColor('#DD00FF')
        time.sleep(0.05)
        self.loadAndSetColor('#EE00FF')
        time.sleep(0.05)
        self.loadAndSetColor('#FF00FF')
        time.sleep(0.05)
        self.loadAndSetColor('#FF00EE')
        time.sleep(0.05)
        self.loadAndSetColor('#FF00DD')
        time.sleep(0.05)
        self.loadAndSetColor('#FF00CC')
        time.sleep(0.05)
        self.loadAndSetColor('#FF00BB')
        time.sleep(0.05)
        self.loadAndSetColor('#FF00AA')
        time.sleep(0.05)
        self.loadAndSetColor('#FF0099')
        time.sleep(0.05)
        self.loadAndSetColor('#FF0088')
        time.sleep(0.05)
        self.loadAndSetColor('#FF0077')
        time.sleep(0.05)
        self.loadAndSetColor('#FF0066')
        time.sleep(0.05)
        self.loadAndSetColor('#FF0055')
        time.sleep(0.05)
        self.loadAndSetColor('#FF0044')
        time.sleep(0.05)
        self.loadAndSetColor('#FF0033')
        time.sleep(0.05)
        self.loadAndSetColor('#FF0022')
        time.sleep(0.05)
        self.loadAndSetColor('#FF0011')
        time.sleep(0.05)
        self.loadAndSetColor('#FF0000')
        time.sleep(0.05)
        self.loadAndSetColor('#EE0000')
        time.sleep(0.05)
        self.loadAndSetColor('#DD0000')
        time.sleep(0.05)
        self.loadAndSetColor('#CC0000')
        time.sleep(0.05)
        self.loadAndSetColor('#BB0000')
        time.sleep(0.05)
        self.loadAndSetColor('#AA0000')
        time.sleep(0.05)
        self.loadAndSetColor('#990000')
        time.sleep(0.05)
        self.loadAndSetColor('#880000')
        time.sleep(0.05)
        self.loadAndSetColor('#770000')
        time.sleep(0.05)
        self.loadAndSetColor('#660000')
        time.sleep(0.05)
        self.loadAndSetColor('#550000')
        time.sleep(0.05)
        self.loadAndSetColor('#440000')
        time.sleep(0.05)
        self.loadAndSetColor('#330000')
        time.sleep(0.05)
        self.loadAndSetColor('#220000')
        time.sleep(0.05)
        self.loadAndSetColor('#110000')
        time.sleep(0.05)
        self.loadAndSetColor('#000000')
        time.sleep(0.5)
        self.setColor(0.4,0,0)
Пример #11
0
adxl345 = ADXL345()
client = dropbox.client.DropboxClient('<ENTER YOUR DROPBOX KEY HERE>')
#print('linked account: ', client.account_info())
logging.info('linked account: ', client.account_info())

axes = adxl345.getAxes(True)
#print("ADXL345 on address 0x%x:" % (adxl345.address))
logging.info("ADXL345 on address 0x%x:" % (adxl345.address))
t = 0
x_av = 0
y_av = 0
x_values = []
y_values = []
#print('Calibrating....')
logging.info('Calibrating....')
led.blink(on_time=0.1, off_time=0.1, on_color=(0, 0, 1), n=50, background=True)
while t < 100:
    axes = adxl345.getAxes(True)
    x = axes['x']
    y = axes['y']
    #    print(x)
    x_values.append(x)
    y_values.append(y)
    time.sleep(0.1)
    t += 1
x_av = numpy.mean(x_values)
y_av = numpy.mean(y_values)
x_range = numpy.max(x_values) - numpy.min(x_values)
y_range = numpy.max(y_values) - numpy.min(y_values)
logging.info('Set mean x: ' + str(x_av))
logging.info('Set range x: ' + str(x_range))
Пример #12
0
    speed=2

  print(state)
  if ( state is 'init'):
    state = 'init2green'
    led.blink(speed,speed,on_color=(0,1,0))
  elif ( state is 'init2green'):
    state = 'green2yellow'
    led.blink(speed,speed,on_color = (1,0.7,0))
  elif ( state is 'green2yellow'):
    state = 'yellow2red'
    led.blink(speed,speed,on_color = (1,0,0))
  elif ( state is 'yellow2red'):
    state = 'red2yellow'
    led.blink(speed,speed,on_color = (1,0.7,0))
  elif ( state is 'red2yellow'):
    state = 'yellow2green'
    led.blink(speed,speed,on_color = (0,1,0))
  elif ( state is 'yellow2green'):
    state = 'green2yellow'
    led.blink(speed,speed,on_color = (1,1,0))
  elif ( state is 'error'):
    state = 'init'
    led.blink(speed,speed,on_color = (1,1,1))
  print(state)

led.blink(speed,speed)
button.when_pressed = state_transition

pause()
Пример #13
0
led3 = RGBLED(8,7,12)

button = Button(21)

mode1 = (1, 0, 0) # Red
mode2 = (0, 1, 0) # Green

while True:	
	led1.on()
	led2.on()
	led3.on()

	button.wait_for_press()
	button.wait_for_release()

	led1.blink()
	sleep(0.4)
	led2.blink()
	sleep(0.4)
	led3.blink()

	button.wait_for_press()
	button.wait_for_release()
	
	led1.pulse()
	sleep(0.4)
	led2.pulse()
	sleep(0.4)
	led3.pulse()
	
	button.wait_for_press()
Пример #14
0
class Beacon(object):

    connectState = ConnectState.Disconnected
    failConnectCount = 0
    configData = None
    commandsData = None
    client = None
    soundDir = os.path.join(launchDir, 'sounds/')
    rgbLED = None
    button = None
    buttonHoldTime = None
    persistentLedRule = None

    def __init__(self):
        logging.info("Beacon service initialized")

        with open(os.path.join(launchDir, 'beacon.json')) as data_file:
            self.configData = json.load(data_file)
        #need to account for no json data loaded

        if (self.configData.get("gpio")):
            gpioData = self.configData["gpio"]

            if gpioData.get("button"):
                self.button = Button(int(gpioData["button"]))
                self.button.when_released = self.buttonReleased
                self.button.when_held = self.buttonHeld
            else:
                logging.error(
                    "config json gpio object missing required button id")

            if gpioData.get("red_led") and gpioData.get(
                    "green_led") and gpioData.get("blue_led"):
                self.rgbLED = RGBLED(int(gpioData["red_led"]),
                                     int(gpioData["green_led"]),
                                     int(gpioData["blue_led"]), False,
                                     (0, 0, 0), True)
            else:
                logging.error(
                    "config json gpio object missing required redled, greenled, and blueled ids"
                )

        else:
            logging.error("config json missing require gpio object")

        if self.configData.get("directories"):
            dirObj = self.configData["directories"]
            if dirObj.get("sound"):
                soundDir = dirObj["sound"]

        if self.configData.get("commands"):
            self.commandsData = self.configData["commands"]

        self.ledDisplay(LedDisplayRule(0, 1, 0, 1, 1))
        sleep(1)

        self.client = MQTTClient(self.configData["credentials"]["username"],
                                 self.configData["credentials"]["key"])
        self.client.on_connect = self.connected
        self.client.on_disconnect = self.disconnected
        self.client.on_message = self.message

        while True:
            if self.connectState == ConnectState.Disconnected:
                self.connect()
            elif self.connectState == ConnectState.PendingReconnect:
                self.reconnect()
            try:
                self.client.loop()
            except RuntimeError:
                logging.exception("runtime error caught from mqtt client loop")
                self.reconnect()

    def buttonHeld(self):
        self.buttonHoldTime = time.time()

    def buttonReleased(self):
        if self.buttonHoldTime is not None:
            heldTime = time.time() - self.buttonHoldTime + 1
            self.buttonHoldTime = None
            print heldTime
            if heldTime > 5:
                self.ledDisplay(LedDisplayRule(1, 0, 0, 3, .5))
                sleep(2)
                self.stopLED()
                os.system('sudo shutdown -r now')
        else:
            self.stopLED()
            self.persistentLedRule = None
            print self.commandsData
            if mixer.get_init() and mixer.music.get_busy():
                mixer.music.stop()
                mixer.quit()
            elif self.commandsData is not None:
                self.client.publish(self.configData["feeds"]["outbound"],
                                    self.commandsData[0])

    def message(self, client, feed_id, payload):
        msgStr = 'Feed {0} received new value: {1}'.format(feed_id, payload)
        log_data = ""
        with open(logFilePath, 'r') as myfile:
            log_data = myfile.read().replace('\n', '')
        if log_data.find(msgStr) == -1 or testing:
            logging.info(msgStr)
            messageData = None
            try:
                messageData = json.loads(payload)
            except:
                pass
            sound = None
            volume = 1
            redVal = 0
            greenVal = 1
            blueVal = 0
            blinkCount = 1
            blinkRate = 1
            persistent = False
            pulse = False
            if self.configData.get("sounds"):
                sound = self.configData["sounds"]["default"]
            if messageData is not None:
                if messageData.get("sound"):
                    sound = self.configData["sounds"][messageData["sound"]]
                if messageData.get("persistent") and str(
                        messageData["persistent"]).lower() == "true":
                    persistent = True
                if messageData.get("volume") is not None:
                    volume = float(messageData.get("volume"))
                if messageData.get("blinkCount") is not None:
                    blinkCount = int(messageData.get("blinkCount"))
                if messageData.get("blinkRate") is not None:
                    blinkRate = float(messageData.get("blinkRate"))
                if messageData.get("pulse") is not None and str(
                        messageData["pulse"]).lower() == "true":
                    pulse = True
                if messageData.get("color") is not None:
                    try:
                        colorArr = str(messageData.get("color")).split("/")
                        redVal = float(colorArr[0])
                        greenVal = float(colorArr[1])
                        blueVal = float(colorArr[2])
                    except:
                        pass

            if sound is not None:
                mixer.init()
                mixer.music.set_volume(volume)
                mixer.music.load(self.soundDir + sound)
                mixer.music.play()
            self.ledDisplay(
                LedDisplayRule(redVal, greenVal, blueVal, blinkCount,
                               blinkRate, pulse, persistent))

    def stopLED(self):
        self.rgbLED._stop_blink()
        self.rgbLED.off()

    def ledDisplay(self, rule):
        self.stopLED()
        blinkCount = rule.blinkCount
        if (rule.persistent):
            blinkCount = None
            self.persistentLedRule = rule
        if (rule.pulse):
            self.rgbLED.pulse(fade_in_time=rule.blinkRate,
                              fade_out_time=rule.blinkRate,
                              on_color=(rule.r, rule.g, rule.b),
                              off_color=(0, 0, 0),
                              n=blinkCount,
                              background=True)
        else:
            self.rgbLED.blink(on_time=rule.blinkRate,
                              off_time=rule.blinkRate,
                              fade_in_time=0,
                              fade_out_time=0,
                              on_color=(rule.r, rule.g, rule.b),
                              off_color=(0, 0, 0),
                              n=blinkCount,
                              background=True)

    def connected(self, client):
        logging.info("Connected to Adafruit IO")
        self.connectState = ConnectState.Connected
        self.failConnectCount = 0
        self.client.subscribe(self.configData["feeds"]["inbound"])

    def disconnected(self, client):
        logging.info('Disconnected from AdafruitIO')
        self.connectState = ConnectState.Disconnected
        self.reconnect()

    def connect(self):
        logging.info("init connect to Adafruit IO")
        self.connectState = ConnectState.Connecting
        try:
            self.client.connect()
        except Exception as e:
            logging.exception("Exception from Adafruit client connect")
            self.reconnect()

    def reconnect(self):
        self.failConnectCount += 1
        logging.info('pending Adafruit IO reconnect - failcount=' +
                     str(self.failConnectCount))
        self.connectState = ConnectState.Connecting
        sleep(10)
        self.connect()
Пример #15
0
from gpiozero import RGBLED
from colorzero import Color
from time import sleep

#define pins
led = RGBLED(green=10,red=9,blue=11,active_high=False) # common anode RBG LED!

led.on()
sleep(1)
led.off()

led.color = Color("yellow")
sleep(1)
led.color = Color("purple")
sleep(1)
led.toggle() #invert
sleep(1)
led.blink(on_time=1.5, off_time=0.5, fade_in_time=0.5, fade_out_time=0.5, on_color=(1, 0.3, 1), off_color=(0, 1, 0), n=10, background=False)


led.off()

print("done")
led.close()

Пример #16
0
from gpiozero import RGBLED
from time import sleep
led = RGBLED(red=17, green=18, blue=19)
delay = 0.02

while True:
    led.blink(on_time=0, off_time=0, \
              fade_in_time=2, fade_out_time=2, \
              on_color=(1,0,0), off_color=(0,0,0))
    sleep(4)

    led.blink(on_time=0, off_time=0, \
              fade_in_time=2, fade_out_time=2, \
              on_color=(0,1,0), off_color=(0,0,0))
    sleep(4)

    led.blink(on_time=0, off_time=0, \
              fade_in_time=2, fade_out_time=2, \
              on_color=(0,0,1), off_color=(0,0,0))
    sleep(4)
Пример #17
0
class FabmanBridge(object):
    def __init__(self,
                 config=None,
                 config_file="fabman.json"
                 ):  # if no config is given read config from "fabman.json"
        #try:
        # default values
        self.config = {
            "api_url_base": "https://fabman.io/api/v1/",
            "heartbeat_interval": 30,
            "left_button": 24,
            "reader_type": "MFRC522",
            "led_r": 17,
            "led_g": 27,
            "led_b": 22,
            "display": "SSD1306_128_32",
            "relay": 26,
            "buzzer": 18
        }

        if (config is None):
            self.config_file = config_file
            self.load_config(self.config_file)
        else:
            self.config_file = None
            pprint.pprint(config)
            self.config.update(config)

        if ("api_token" in self.config):
            self.api_header = {
                'Content-Type':
                'application/json',
                'Authorization':
                'Bearer {0}'.format(self.config['bridge_api_token'])
            }
        else:
            logging.warning(
                'Not api-token defined: Cannot access Fabman via Bridge API')
        self.session_id = None
        self.next_heartbeat_call = time.time()
        self.rgbled = RGBLED(self.config["led_r"], self.config["led_g"],
                             self.config["led_b"])
        self.buzzer = Buzzer(self.config["buzzer"])
        self.relay = Relay(self.config["relay"], 0)
        GPIO.setwarnings(False)

        if (self.config["reader_type"] == "MFRC522"):
            #self.reader = SimpleMFRC522()
            #self.reader = SimpleMFRC522()
            self.reader = MFRC522.MFRC522(dev=1)
            self.chip_type = "nfca"
        elif (self.config["reader_type"] == "Gwiot7941E"):
            #print ("setze reader")
            self.reader = Gwiot7941E()
            self.chip_type = "em4102"
        if (self.config["heartbeat_interval"] > 0):
            self._start_heartbeat_thread()
        '''
            if ("stop_button" in self.config and not(self.config["stop_button"] is None)):
                GPIO.setmode(GPIO.BCM) #GPIO.setmode(GPIO.BOARD)  
                GPIO.setup(self.config["stop_button"], GPIO.IN, pull_up_down=GPIO.PUD_UP)
                GPIO.add_event_detect(self.config["stop_button"], GPIO.FALLING, callback=self._callback_stop_button, bouncetime=300)
            '''
        if ("left_button" in self.config
                and not (self.config["left_button"] is None)):
            GPIO.setmode(GPIO.BCM)  #GPIO.setmode(GPIO.BOARD)
            GPIO.setup(self.config["left_button"],
                       GPIO.IN,
                       pull_up_down=GPIO.PUD_UP)
        if ("right_button" in self.config
                and not (self.config["right_button"] is None)):
            GPIO.setmode(GPIO.BCM)  #GPIO.setmode(GPIO.BOARD)
            GPIO.setup(self.config["right_button"],
                       GPIO.IN,
                       pull_up_down=GPIO.PUD_UP)
        #if ("left_button_pin" in self.config and not(self.config["left_button_pin"] is None)):
        #	self.left_button = Button(self.config["left_button_pin"], pull_up=True, bounce_time=0.3)
        #if ("right_button_pin" in self.config and not(self.config["right_button_pin"] is None)):
        #	self.right_button = Button(pin=self.config["right_button_pin"], pull_up=True, bounce_time=0.3)
        if (self.config["display"] == "sh1106"):  # 1,3" I2C OLED Display
            self.device = get_device(("--display", self.config["display"]))

        self.screen_message = ""

    #except Exception as e:
    #	logging.error('Function FabmanBridge.__init__ raised exception (' + str(e) + ')')

    def save_config(self, filename="fabman.json"):
        try:
            with open(filename, 'w') as fp:
                json.dump(self.config, fp, sort_keys=True, indent=4)
            return True
        except Exception as e:
            logging.error(
                'Function FabmanBridge.save_config raised exception (' +
                str(e) + ')')
            return False

    def load_config(self, filename="fabman.json"):
        try:
            with open(filename, 'r') as fp:
                file_config = json.load(fp)
                self.config.update(file_config)
            return self.config
        except Exception as e:
            logging.error(
                'Function FabmanBridge.load_config raised exception (' +
                str(e) + ')')
            return False

    def access(self, user_id):  # user_id can be email address or rfid key
        try:
            if (user_id):
                if ("@" in str(user_id)):  # authenticate with email address
                    data = {'emailAddress': user_id, 'configVersion': 0}
                else:  # authenticate with rfid key
                    data = {
                        "keys": [{
                            "type": self.chip_type,
                            "token": user_id
                        }],
                        "configVersion": 0
                    }
                api_url = '{0}bridge/access'.format(
                    self.config["api_url_base"])
                response = requests.post(api_url,
                                         headers=self.api_header,
                                         json=data)
                if (response.status_code == 200 and json.loads(
                        response.content.decode('utf-8'))['type']
                        == "allowed"):
                    logging.info('Bridge started successfully.')
                    #self.display_text("Access granted\n\n\n<-STOP")
                    self.rgbled.color = Color('green')
                    self.session_id = json.loads(
                        response.content.decode('utf-8'))["sessionId"]
                    return True
                else:
                    logging.warning('Bridge could not be started (user_id: ' +
                                    str(user_id) + ')')

                    pprint.pprint(json.loads(response.content.decode('utf-8')))

                    #self.display_error("Access\ndenied")
                    #self.display_text("Access denied")
                    #self.display_text("Access denied",3)
                    return False
            else:
                logging.warning("No user_id set for /bridge/access")
        except Exception as e:
            logging.error('Function FabmanBridge.access raised exception (' +
                          str(e) + ')')
            return False

    def stop(self, metadata=None, charge=None):
        try:
            api_url = '{0}bridge/stop'.format(self.config["api_url_base"])

            data = {
                "stopType": "normal",
                "currentSession": {
                    "id": self.session_id
                }
            }
            if (metadata is not None):
                data['currentSession'].update({'metadata': metadata})
            if (charge is not None):
                print("UPDATE CHARGE DURING BRIDGE STOP:")
                data['currentSession'].update({'charge': charge})
                pprint.pprint(data['currentSession'])
            '''
            if (metadata is None): # do not set metadata if no data available
                #data = { "stopType": "normal", "currentSession": { "id": sessionId, "idleDurationSeconds": idleTime } }
                data = { "stopType": "normal", "currentSession": { "id": self.session_id } }
            else: # set metadata, if available
                try:
                    data = { "stopType": "normal", "currentSession": { "id": sessionId, "idleDurationSeconds": idleTime, "metadata": metadata, "charge": create_charge(get_metadata()) } }
                except: # no charge data available
                    data = { "stopType": "normal", "currentSession": { "id": sessionId, "idleDurationSeconds": idleTime, "metadata": metadata } }
            
                    data = { 
                            "stopType": "normal", 
                            "currentSession": { 
                                                "id": sessionId, 
                                                "idleDurationSeconds": idleTime, 
                                                "metadata": metadata, 
                                                "charge": create_charge(get_metadata()) 
                                              } 
                           }		
            '''

            response = requests.post(api_url,
                                     headers=self.api_header,
                                     json=data)

            if response.status_code == 200 or response.status_code == 204:
                #self.user_id = None
                self.session_id = None
                logging.info('Bridge stopped successfully.')
                #self.rgbled.off("g")
                self.rgbled.off()

                return True
            else:
                logging.error('Bridge could not be stopped (status code ' +
                              str(response.status_code) + ')')
                pprint.pprint(data)
                self.display_error()
                return False
        except Exception as e:
            logging.error('Function FabmanBridge.stop raised exception (' +
                          str(e) + ')')
            return False

    def read_key(self):
        try:
            if (self.config["reader_type"] == "MFRC522"):
                #return str(hex(self.reader.read_id()))[2:10]
                continue_reading = True
                while continue_reading:
                    # Scan for cards
                    (status, TagType) = self.reader.MFRC522_Request(
                        self.reader.PICC_REQIDL)
                    # If a card is found
                    if status == self.reader.MI_OK:
                        logging.debug("Card detected")
                        continue_reading = False
                        # Get the UID of the card
                        (status, uid) = self.reader.MFRC522_SelectTagSN()
                        # If we have the UID, continue
                        if status == self.reader.MI_OK:
                            uid_string = ""
                            for i in uid:
                                uid_string += format(i, '02X')
                            logging.debug("Card uid: " + uid_string)
                            return uid_string
                        else:
                            logging.debug("Card authentication error")
            elif (self.config["reader_type"] == "Gwiot7941E"):
                uid_string = self.reader.read()
                return uid_string
            else:
                logging.error("Undefined reader type")
                return False
        except Exception as e:
            logging.error('Function FabmanBridge.read_key raised exception (' +
                          str(e) + ')')
            return False

    def is_on(self):
        try:
            if (self.session_id is None):
                return False
            else:
                return True
        except Exception as e:
            logging.error('Function FabmanBridge.is_on raised exception (' +
                          str(e) + ')')
            return False

    def is_off(self):
        try:
            return not (self.is_on())
        except Exception as e:
            logging.error('Function FabmanBridge.is_off raised exception (' +
                          str(e) + ')')
            return False

    def display_error(self, message=None):
        try:
            #self.rgbled.on("r",0.1)
            #self.rgbled.off("r",0.1)
            #self.rgbled.on("r",0.1)
            #self.rgbled.off("r",0.1)
            #self.rgbled.on("r",0.1)
            #self.rgbled.off("r")
            self.rgbled.blink(0.1, 0.1, 0, 0, Color('red'), Color('black'), 3,
                              True)
            if (message is not None):
                logging.error(message)
                self.display_text(message, 3)
                print(message)
            return True
        except Exception as e:
            logging.error(
                'Function FabmanBridge.display_error raised exception (' +
                str(e) + ')')
            return False

    def display_warning(self, message=None):
        try:
            #self.rgbled.on("b",0.1)
            #self.rgbled.off("b",0.1)
            #self.rgbled.on("b",0.1)
            #self.rgbled.off("b",0.1)
            #self.rgbled.on("b",0.1)
            #self.rgbled.off("b")
            self.rgbled.blink(0.1, 0.1, 0, 0, Color('yellow'), Color('black'),
                              3, True)
            if (message is not None):
                logging.warning(message)
                self.display_text(message, 3)
                print(message)
            return True
        except Exception as e:
            logging.error(
                'Function FabmanBridge.display_warning raised exception (' +
                str(e) + ')')
            return False

    def display_text(self, text="", duration=None):  # duration None = forever
        try:
            if (
                    duration is None
            ):  # new text remains "forever" - no old text to recover afterwards
                self.screen_message = text

            #print("************interval*****" + str(self.config["display"].startswith('SSD1306')))
            if (self.config["display"] == "sh1106"):  # 1,3" I2C OLED Display

                def display_line(draw,
                                 text,
                                 font_size=15,
                                 y=0,
                                 x=0,
                                 font='C&C Red Alert [INET].ttf'):
                    # use custom font
                    font_path = os.path.abspath(
                        os.path.join(os.path.dirname(__file__), 'fonts', font))
                    #font2 = ImageFont.truetype(font_path, 12)
                    #print (font_path)
                    font = ImageFont.truetype(font_path, font_size)
                    #with canvas(device) as draw:
                    draw.text((x, y), str(text), font=font, fill="white")

                if (type(text).__name__ == "str"):
                    default_size = 15
                    #print(type(text).__name__)
                    line_array = text.splitlines()
                    lines = []
                    #pprint.pprint(line_array)
                    for i in range(len(line_array)):
                        #print (line_array[i])
                        lines.insert(i, {
                            "text": line_array[i],
                            "size": default_size
                        })
                    #pprint.pprint(lines)
                #self.device = get_device(("--display", self.config["display"]))
                with canvas(self.device) as draw:
                    y = 0
                    for line in lines:
                        #print(line['text'])
                        display_line(draw, line['text'], line['size'], y)
                        y += (line['text'].count("\n") + 1) * line['size']

                if (duration is not None):
                    time.sleep(duration)

                    with canvas(self.device) as draw:
                        y = 0
                        for line in lines:
                            #print(line['text'])
                            display_line(draw=draw,
                                         text=self.screen_message,
                                         y=y)
                            y += (line['text'].count("\n") + 1) * line['size']

            elif (self.config["display"].startswith('SSD1306')):

                # Raspberry Pi pin configuration:
                RST = None  # on the PiOLED this pin isnt used

                if (self.config["display"] == "SSD1306_128_32"):
                    # 128x32 display with hardware I2C:
                    disp = Adafruit_SSD1306.SSD1306_128_32(rst=RST)
                elif (self.config["display"] == "SSD1306_128_64"):
                    # 128x64 display with hardware I2C:
                    disp = Adafruit_SSD1306.SSD1306_128_64(rst=RST)

                # Note you can change the I2C address by passing an i2c_address parameter like:
                # disp = Adafruit_SSD1306.SSD1306_128_64(rst=RST, i2c_address=0x3C)

                # Alternatively you can specify an explicit I2C bus number, for example
                # with the 128x32 display you would use:
                # disp = Adafruit_SSD1306.SSD1306_128_32(rst=RST, i2c_bus=2)

                # 128x32 display with hardware SPI:
                # disp = Adafruit_SSD1306.SSD1306_128_32(rst=RST, dc=DC, spi=SPI.SpiDev(SPI_PORT, SPI_DEVICE, max_speed_hz=8000000))

                # 128x64 display with hardware SPI:
                # disp = Adafruit_SSD1306.SSD1306_128_64(rst=RST, dc=DC, spi=SPI.SpiDev(SPI_PORT, SPI_DEVICE, max_speed_hz=8000000))

                # Alternatively you can specify a software SPI implementation by providing
                # digital GPIO pin numbers for all the required display pins.  For example
                # on a Raspberry Pi with the 128x32 display you might use:
                # disp = Adafruit_SSD1306.SSD1306_128_32(rst=RST, dc=DC, sclk=18, din=25, cs=22)

                # Initialize library.
                disp.begin()

                # Clear display.
                disp.clear()
                disp.display()

                # Create blank image for drawing.
                # Make sure to create image with mode '1' for 1-bit color.
                width = disp.width
                height = disp.height
                image = Image.new('1', (width, height))

                # Get drawing object to draw on image.
                draw = ImageDraw.Draw(image)

                # Draw a black filled box to clear the image.
                draw.rectangle((0, 0, width, height), outline=0, fill=0)

                # Load default font.
                font = ImageFont.load_default()

                # Alternatively load a TTF font.  Make sure the .ttf font file is in the same directory as the python script!
                # Some other nice fonts to try: http://www.dafont.com/bitmap.php
                # font = ImageFont.truetype('Minecraftia.ttf', 8)

                # Draw a black filled box to clear the image.
                draw.rectangle((0, 0, width, height), outline=0, fill=0)

                # Draw some shapes.
                # First define some constants to allow easy resizing of shapes.
                x = 0
                padding = -2
                top = padding
                bottom = height - padding
                linespacing = 8

                # Write four lines of text
                lines = text.split("\n")
                if (len(lines) >= 1):
                    draw.text((x, top + 0 * linespacing),
                              lines[0],
                              font=font,
                              fill=255)
                if (len(lines) >= 2):
                    draw.text((x, top + 1 * linespacing),
                              lines[1],
                              font=font,
                              fill=255)
                if (len(lines) >= 3):
                    draw.text((x, top + 2 * linespacing),
                              lines[2],
                              font=font,
                              fill=255)
                if (len(lines) >= 4):
                    draw.text((x, top + 3 * linespacing),
                              lines[3],
                              font=font,
                              fill=255)

                # Display image.
                disp.image(image)
                disp.display()

                if (duration is not None):
                    time.sleep(duration)
                    # clear display
                    disp.clear()
                    disp.display()
                    # recover previous screen message
                    lines = self.screen_message.split("\n")
                    if (len(lines) >= 1):
                        draw.text((x, top + 0 * linespacing),
                                  lines[0],
                                  font=font,
                                  fill=255)
                    if (len(lines) >= 2):
                        draw.text((x, top + 1 * linespacing),
                                  lines[1],
                                  font=font,
                                  fill=255)
                    if (len(lines) >= 3):
                        draw.text((x, top + 2 * linespacing),
                                  lines[2],
                                  font=font,
                                  fill=255)
                    if (len(lines) >= 4):
                        draw.text((x, top + 3 * linespacing),
                                  lines[3],
                                  font=font,
                                  fill=255)

            else:
                logging.warning('Unsupported display type: ' +
                                str(self.config["display"]))
            return True
        except Exception as e:
            logging.error(
                'Function FabmanBridge.display_text raised exception (' +
                str(e) + ')')
            return False

    def _start_heartbeat_thread(self):
        try:
            #print datetime.datetime.now()
            api_url = '{0}bridge/heartbeat'.format(self.config["api_url_base"])
            data = {'configVersion': 0}
            response = requests.post(api_url,
                                     headers=self.api_header,
                                     json=data)
            if response.status_code == 200:
                response = json.loads(response.content.decode('utf-8'))
                logging.debug("Heartbeat sent")
            else:
                logging.warning("Heartbeat failed")
            self.next_heartbeat_call += self.config["heartbeat_interval"]
            heartbeat_thread = threading.Timer(
                self.next_heartbeat_call - time.time(),
                self._start_heartbeat_thread)
            heartbeat_thread.daemon = True
            heartbeat_thread.start()
        except Exception as e:
            logging.error(
                'Function FabmanBridge._start_heartbeat_thread raised exception ('
                + str(e) + ')')
            return False

    '''
    def _callback_stop_button(self, channel):
        try:
            #print("self.config[stop_button] = " + str(self.config["stop_button"]))
            #print("channel = " + str(channel))
            if (self.config["stop_button"] == channel and self.is_on()):
                logging.debug("Switching off ...")
                self.stop()
            #else:
            #	print "stop button (gpio" + str(channel) + ") pressed."
            #	print "stop_button: " + str(self.config["stop_button"])
            #	print "channel (muss gleich sein wie stop_button): " + str(channel)
            #	print "is_on (muss True sein): " +str(self.is_on())
            #	print "stop() wurde nicht aufgerufen"
            #	self.display_warning()
        except Exception as e: 
            logging.error('Function FabmanBridge._callback_stop_button raised exception (' + str(e) + ')')
            return False
    '''
    '''
    def run(self):
        try:
            logging.info("Bridge started.")
            while (True):
                if (self.is_off()):
                    logging.debug("Ready to read nfc key ...")
                    self.display_text("Show card to start")
                    key = self.read_key()
                    if (key != False and key is not None):
                        self.access(key)
        except Exception as e: 
            logging.error('Function FabmanBridge.run raised exception (' + str(e) + ')')
            return False
    '''

    def send_email(self, subject, text, email_to=None):
        try:

            # default values from fabman.json
            if (email_to is None):
                email_to = self.config["email_operator"]

            server = smtplib.SMTP(self.config["email_smtp"],
                                  self.config["email_port"])
            server.ehlo()
            server.starttls()
            server.login(self.config["email_sender"],
                         self.config["email_password"])

            msg = MIMEMultipart('alternative')
            msg.set_charset('utf8')
            msg['FROM'] = self.config["email_sender"]
            msg['Subject'] = Header(subject.encode('utf-8'), 'UTF-8').encode()
            msg['To'] = email_to
            _attach = MIMEText(text.encode('utf-8'), 'html', 'UTF-8')
            msg.attach(_attach)

            server.sendmail(self.config["email_sender"], [email_to],
                            msg.as_string())

            logging.info('Email "' + subject + '" sent to ' + email_to)
            #logging.debug(text)
            server.quit()

        except Exception as e:
            logging.error('Sending email "' + subject + '" to ' + email_to +
                          'FAILED: ' + text)
            logging.error(
                'Function FabmanBridge.send_email raised exception (' +
                str(e) + ')')
            server.quit()
            return False
Пример #18
0
                     active_high=False,
                     initial_value=(0, 0, 0))
    #   missile_LED = LED(missile_LED_P, active_high=True, initial_value=True)

    lcd_RELAY = DigitalOutputDevice(lcd_RELAY_P, initial_value=False)
    vol_mid = vol_green + (vol_red - vol_green) / 2

    if os == "moode":  #Setzten einer Start-Lautstaerke
        startupvol = str(20)
        getoutput("/var/www/vol.sh " + startupvol)

    #Laesst die Rotary LED aufleuchten/blinken um einen Abgeschlossenen Startvorgang zu signalisieren
    rot_RGB.blink(on_time=1,
                  off_time=0.3,
                  fade_in_time=0.0,
                  fade_out_time=0.2,
                  on_color=(0, 0, 0),
                  off_color=(1, 0, 0),
                  n=1,
                  background=False)
    rot_RGB.blink(on_time=0.3,
                  off_time=0.3,
                  fade_in_time=0.2,
                  fade_out_time=0.2,
                  on_color=(0, 1, 1),
                  off_color=(1, 0, 1),
                  n=1,
                  background=False)
    rot_RGB.blink(on_time=0.3,
                  off_time=0.3,
                  fade_in_time=0.2,
                  fade_out_time=0.2,