Example #1
0
    def show(self, position=1):
        from blink import Blink
        blink = Blink()
        screen_geometry = blink.desktop().screenGeometry(self)
        available_geometry = blink.desktop().availableGeometry(self)
        main_window_geometry = blink.main_window.geometry()
        main_window_framegeometry = blink.main_window.frameGeometry()

        horizontal_decorations = main_window_framegeometry.width() - main_window_geometry.width()
        vertical_decorations = main_window_framegeometry.height() - main_window_geometry.height()
        width = limit(self.sizeHint().width(), min=self.minimumSize().width(), max=min(self.maximumSize().width(), available_geometry.width()-horizontal_decorations))
        height = limit(self.sizeHint().height(), min=self.minimumSize().height(), max=min(self.maximumSize().height(), available_geometry.height()-vertical_decorations))
        total_width = width + horizontal_decorations
        total_height = height + vertical_decorations
        x = limit(screen_geometry.center().x() - total_width/2, min=available_geometry.left(), max=available_geometry.right()-total_width)
        if position is None:
            y = -1
        elif position % 2 == 0:
            y = screen_geometry.center().y() + (position-1)*total_height/2
        else:
            y = screen_geometry.center().y() - position*total_height/2
        if available_geometry.top() <= y <= available_geometry.bottom() - total_height:
            self.setGeometry(x, y, width, height)
        else:
            self.resize(width, height)

        self.position = position
        super(PendingWatcherDialog, self).show()
Example #2
0
 def initialize(self):
     """Initialize WinSparkle library, it will try to fetch updates in the background"""
     from blink import Blink, __version__
     application = Blink()
     settings = SIPSimpleSettings()
     winsparkle_set_appcast_url(settings.server.updater_url)
     winsparkle_set_app_details(application.organizationName(), application.applicationName(), __version__)
     winsparkle_init()
Example #3
0
    def connect():
        """Connect to internet"""
        my_networks = json.loads(open('networks.json').read())
        led16 = Blink(16)
        led2 = Blink(2)
        sta_if = network.WLAN(network.STA_IF)

        # scan what’s available
        available_networks = []
        for net in sta_if.scan():
            ssid = net[0].decode("utf-8")
            bssid = net[1]
            strength = net[3]
            available_networks.append(dict(ssid=ssid, bssid=bssid, strength=strength))
        # Sort fields by strongest first in case of multiple SSID access points
        available_networks.sort(key=lambda station: station["strength"], reverse=True)

        if not sta_if.isconnected():
            led16.blink(2, 0.2)
            for config in my_networks['known_networks']:
                for ssid in available_networks:
                    if config["ssid"] == ssid["ssid"]:
                        print('connecting to network {0} ...'.format(config["ssid"]))
                        sta_if.active(True)
                        sta_if.connect(config["ssid"], config["password"])

        print('network config:', sta_if.ifconfig())
        led2.blink(1, 0.2)
Example #4
0
 def _test_download_thumbnail(self):
     '''doesn't work'''
     b = Blink()
     b.connect()
     network_id = b.networks[0]['id']
     events = b.events(network_id)
     event = events[0]
     b.download_thumbnail(event)
Example #5
0
    def show(self, position=1):
        from blink import Blink
        blink = Blink()
        screen_geometry = blink.desktop().screenGeometry(self)
        available_geometry = blink.desktop().availableGeometry(self)
        main_window_geometry = blink.main_window.geometry()
        main_window_framegeometry = blink.main_window.frameGeometry()

        horizontal_decorations = main_window_framegeometry.width(
        ) - main_window_geometry.width()
        vertical_decorations = main_window_framegeometry.height(
        ) - main_window_geometry.height()
        width = limit(self.sizeHint().width(),
                      min=self.minimumSize().width(),
                      max=min(
                          self.maximumSize().width(),
                          available_geometry.width() - horizontal_decorations))
        height = limit(self.sizeHint().height(),
                       min=self.minimumSize().height(),
                       max=min(
                           self.maximumSize().height(),
                           available_geometry.height() - vertical_decorations))
        total_width = width + horizontal_decorations
        total_height = height + vertical_decorations
        x = limit(screen_geometry.center().x() - total_width / 2,
                  min=available_geometry.left(),
                  max=available_geometry.right() - total_width)
        if position is None:
            y = -1
        elif position % 2 == 0:
            y = screen_geometry.center().y() + (position -
                                                1) * total_height / 2
        else:
            y = screen_geometry.center().y() - position * total_height / 2
        if available_geometry.top(
        ) <= y <= available_geometry.bottom() - total_height:
            self.setGeometry(x, y, width, height)
        else:
            self.resize(width, height)

        self.position = position
        super(PendingWatcherDialog, self).show()
Example #6
0
 def __init__(self):
     self.config = Config()
     self.not_read_channels = []
     self.blink = Blink()
     self.mattermost_driver = Driver({
         'url':
         self.config.get_string('MATTERMOST', 'url'),
         'login_id':
         self.config.get_string('MATTERMOST', 'login_id'),
         'password':
         self.config.get_string('MATTERMOST', 'password'),
         'verify':
         self.config.get_bool('MATTERMOST', 'verify'),
         'scheme':
         self.config.get_string('MATTERMOST', 'scheme'),
         'port':
         self.config.get_int('MATTERMOST', 'port'),
         'debug':
         self.config.get_bool('MATTERMOST', 'debug')
     })
     self.ignored_channels = self.config.get_string(
         'MATTERMOST', 'ignored_channels').split(',')
     self.server = None
     self.start()
Example #7
0
def process_command(request, cmd):
    # Must be an absolute path (ex: no ~/bin/)

    blink = Blink()

    # Map these directly to --<string> with no interference. Ex: on should map to --on
    direct_map = ['on', 'off', 'red', 'blue', 'green']

    if cmd == 'random' and 'numtimes' in request.GET:
        blink.random(request.GET['numtimes'])
    elif cmd == 'rgb' and 'r' in request.GET and 'g' in request.GET and 'b' in request.GET:
        blink.rgb(request.GET['r'], request.GET['g'], request.GET['b'])
    elif cmd in direct_map:
        blink.cmd('--' + cmd)
    else:
        return HttpResponse('Invalid Command')

    return HttpResponse(0)
Example #8
0
def _main():
    config_fn = os.path.join(os.path.expanduser("~"), '.blinkconfig')
    if os.path.isfile(config_fn):
        with open(config_fn) as f:
            config = yaml.load(f.read())
            if isinstance(config, dict):
                if len(config) == 1:
                    _email, _password = list(config.items())[0]
                if len(config) > 1:
                    raise Exception(
                        'Multiple email/passwords found in .blinkconfig. Please specify which ones to use.'
                    )
            else:
                raise Exception(
                    'File .blinkconfig must be a YAML dictionary. Currently it is a %s.'
                    % type(config))

    args = sys.argv[1:]
    if len(args) > 1 and args[0] == '--archive':
        Blink(_email, _password).archive(args[1])
    else:
        print(f'Usage:\n\t{sys.argv[0]} --archive <dest_dir>')
Example #9
0
 def test_clients(self):
     b = Blink()
     print b.clients()
Example #10
0
 def _test_arm(self):
     b = Blink()
     b.connect()
     print b.arm(b.networks[0])
Example #11
0
 def test_connect(self):
     b = Blink()
     self.assertFalse(b.connected)
     b.connect()
     self.assertTrue(b.connected)
Example #12
0
 def test_sync_modules(self):
     b = Blink()
     b.connect()
     sync_modules = b.sync_modules(b.networks[0])
     print sync_modules
Example #13
0
 def _create_sip_account(self,
                         username,
                         password,
                         email_address,
                         display_name,
                         timezone=None):
     red = '#cc0000'
     if timezone is None and sys.platform != 'win32':
         try:
             timezone = open('/etc/timezone').read().strip()
         except (OSError, IOError):
             try:
                 timezone = '/'.join(
                     os.readlink('/etc/localtime').split('/')[-2:])
             except (OSError, IOError):
                 pass
     enrollment_data = dict(username=username.lower().encode('utf-8'),
                            password=password.encode('utf-8'),
                            email=email_address.encode('utf-8'),
                            display_name=display_name.encode('utf-8'),
                            tzinfo=timezone)
     try:
         settings = SIPSimpleSettings()
         response = urllib2.urlopen(settings.server.enrollment_url,
                                    urllib.urlencode(dict(enrollment_data)))
         response_data = cjson.decode(response.read().replace(r'\/', '/'))
         response_data = defaultdict(lambda: None, response_data)
         if response_data['success']:
             from blink import Blink
             try:
                 certificate_path = None
                 passport = response_data['passport']
                 if passport is not None:
                     certificate_path = Blink().save_certificates(
                         response_data['sip_address'], passport['crt'],
                         passport['key'], passport['ca'])
             except (GNUTLSError, IOError, OSError):
                 pass
             account_manager = AccountManager()
             try:
                 account = Account(response_data['sip_address'])
             except DuplicateIDError:
                 account = account_manager.get_account(
                     response_data['sip_address'])
             account.enabled = True
             account.display_name = display_name or None
             account.auth.password = password
             account.sip.outbound_proxy = response_data['outbound_proxy']
             account.nat_traversal.msrp_relay = response_data['msrp_relay']
             account.xcap.xcap_root = response_data['xcap_root']
             account.tls.certificate = certificate_path
             account.server.conference_server = response_data[
                 'conference_server']
             account.server.settings_url = response_data['settings_url']
             account.save()
             account_manager.default_account = account
             call_in_gui_thread(self.accept)
         elif response_data['error'] == 'user_exists':
             call_in_gui_thread(self.username_editor.addException, username)
         else:
             call_in_gui_thread(
                 setattr, self.create_status_label, 'value',
                 Status(response_data['error_message'], color=red))
     except (cjson.DecodeError, KeyError):
         call_in_gui_thread(setattr, self.create_status_label, 'value',
                            Status('Illegal server response', color=red))
     except urllib2.URLError, e:
         call_in_gui_thread(
             setattr, self.create_status_label, 'value',
             Status('Failed to contact server: %s' % e.reason, color=red))
Example #14
0
 def setUp(self):
     self.b = Blink(self.email, self.password)
     self.b.login()
import pyaudio
import audioop
from blink import Blink
b = Blink()

CHUNK = 1024
WIDTH = 2
CHANNELS = 2
RATE = 44000 # Your device's sample rate is in p.get_device_info_by_index(0)['defaultSampleRate']. 

p = pyaudio.PyAudio()

stream = p.open(format=p.get_format_from_width(WIDTH),
				channels=CHANNELS,
				rate=RATE,
				input=True,
				output=True,
				frames_per_buffer=CHUNK)

print("Listening")

fade = 600
while True:
	data = stream.read(CHUNK)
	max = audioop.rms(data, 2)
	if max > 400:
		b.fade(27, 67, 187, fade, 0)
	if max > 800:
		b.fade(8, 210, 21, fade, 0);
	if max > 1200:
		b.fade(255, 15, 9, fade, 0);
Example #16
0
    def elaborate(self, platform: Platform) -> Module:
        m = Module()

        if platform:
            clk_in = platform.request(platform.default_clk, dir='-')[0]

            # Constants
            pixel_f     = self.timing.pixel_freq
            hsync_front_porch = self.timing.h_front_porch
            hsync_pulse_width = self.timing.h_sync_pulse
            hsync_back_porch  = self.timing.h_back_porch
            vsync_front_porch = self.timing.v_front_porch
            vsync_pulse_width = self.timing.v_sync_pulse
            vsync_back_porch  = self.timing.v_back_porch

            # Clock generator.
            m.domains.sync  = cd_sync  = ClockDomain("sync")
            m.domains.pixel = cd_pixel = ClockDomain("pixel")

            m.submodules.ecp5pll = pll = ECP5PLL()
            pll.register_clkin(clk_in,  platform.default_clk_frequency)
            pll.create_clkout(cd_sync,  platform.default_clk_frequency)
            pll.create_clkout(cd_pixel, pixel_f)

            platform.add_clock_constraint(cd_sync.clk,  platform.default_clk_frequency)
            platform.add_clock_constraint(cd_pixel.clk, pixel_f)

            # VGA signal generator.
            vga_r = Signal(8)
            vga_g = Signal(8)
            vga_b = Signal(8)
            vga_hsync = Signal()
            vga_vsync = Signal()
            vga_blank = Signal()

            m.submodules.vga = vga = VGA(
                resolution_x      = self.timing.x,
                hsync_front_porch = hsync_front_porch,
                hsync_pulse       = hsync_pulse_width,
                hsync_back_porch  = hsync_back_porch,
                resolution_y      = self.timing.y,
                vsync_front_porch = vsync_front_porch,
                vsync_pulse       = vsync_pulse_width,
                vsync_back_porch  = vsync_back_porch,
                bits_x            = 16, # Play around with the sizes because sometimes
                bits_y            = 16  # a smaller/larger value will make it pass timing.
            )
            with m.If(vga.o_beam_y < 240):
                m.d.comb += [
                    vga.i_r.eq(0xff),
                    vga.i_g.eq(0),
                    vga.i_b.eq(0)
                ]
            with m.Else():
                m.d.comb += [
                    vga.i_r.eq(0),
                    vga.i_g.eq(0xff),
                    vga.i_b.eq(0)
                ]
            m.d.comb += [
                vga.i_clk_en.eq(1),
                vga.i_test_picture.eq(0),
                vga_r.eq(vga.o_vga_r),
                vga_g.eq(vga.o_vga_g),
                vga_b.eq(vga.o_vga_b),
                vga_hsync.eq(vga.o_vga_hsync),
                vga_vsync.eq(vga.o_vga_vsync),
                vga_blank.eq(vga.o_vga_blank),
            ]

            vga_out = platform.request("vga")

            m.d.comb += [
                vga_out.red.eq(vga_r[4:]),
                vga_out.green.eq(vga_g[4:]),
                vga_out.blue.eq(vga_b[4:]),
                vga_out.hs.eq(vga_hsync),
                vga_out.vs.eq(vga_vsync)
            ]

            # LED blinky
            counter_width = 28
            countblink = Signal(8)
            m.submodules.blink = blink = Blink(counter_width)
            m.d.comb += [
                countblink.eq(blink.o_led),
                self.o_led[3:5].eq(countblink[6:8]),
                self.o_led[0].eq(vga_vsync),
                self.o_led[1].eq(vga_hsync),
                self.o_led[2].eq(vga_blank),
            ]

        return m
Example #17
0
 def test_regions(self):
     b = Blink()
     print b.regions()
Example #18
0
class BlinkServer(object):
    def __init__(self):
        self.config = Config()
        self.not_read_channels = []
        self.blink = Blink()
        self.mattermost_driver = Driver({
            'url':
            self.config.get_string('MATTERMOST', 'url'),
            'login_id':
            self.config.get_string('MATTERMOST', 'login_id'),
            'password':
            self.config.get_string('MATTERMOST', 'password'),
            'verify':
            self.config.get_bool('MATTERMOST', 'verify'),
            'scheme':
            self.config.get_string('MATTERMOST', 'scheme'),
            'port':
            self.config.get_int('MATTERMOST', 'port'),
            'debug':
            self.config.get_bool('MATTERMOST', 'debug')
        })
        self.ignored_channels = self.config.get_string(
            'MATTERMOST', 'ignored_channels').split(',')
        self.server = None
        self.start()

    def start_wbe_server(self, thread_name):
        self.server = Server(self.blink)

    @asyncio.coroutine
    def socket_handler(self, message):
        print(message)
        self.handle_message(json.loads(message))

    def handle_message(self, json_message):
        if 'event' not in json_message:
            return

        if json_message['event'] == "posted":
            try:
                self.ignored_channels.index(
                    json_message['data']['channel_display_name'])
            except ValueError:
                self.parse_post(json.loads(json_message['data']['post']))
        elif json_message['event'] == "channel_viewed":
            self.mark_chanel_as_read(json_message['data']['channel_id'])

    def parse_post(self, post_data):
        try:
            self.not_read_channels.index(post_data['channel_id'])
        except ValueError:
            self.not_read_channels.append(post_data['channel_id'])
        self.blink.start_unread_blink()

    def mark_chanel_as_read(self, channel_id):
        try:
            index = self.not_read_channels.index(channel_id)
            del self.not_read_channels[index]
            if len(self.not_read_channels) == 0:
                self.blink.stop_unread_blinking()
        except ValueError:
            pass

    def start(self):
        _thread.start_new_thread(self.start_wbe_server, ('webserver', ))
        # todo: polaczenie z gitlabem - nowy MR
        self.mattermost_driver.login()
        while True:
            try:
                self.mattermost_driver.init_websocket(self.socket_handler)
            except Exception:
                print('Reconnecting to websocket')
                time.sleep(60)
Example #19
0
    def elaborate(self, platform: Platform) -> Module:
        m = Module()

        if platform:
            clk_in = platform.request(platform.default_clk, dir='-')[0]

            # Constants
            pixel_f = self.timing.pixel_freq
            hsync_front_porch = self.timing.h_front_porch
            hsync_pulse_width = self.timing.h_sync_pulse
            hsync_back_porch = self.timing.h_back_porch
            vsync_front_porch = self.timing.v_front_porch
            vsync_pulse_width = self.timing.v_sync_pulse
            vsync_back_porch = self.timing.v_back_porch

            # o_wifi_gpio0 = 1 keeps board from rebooting
            # Hold btn0 to let ESP32 take control of the board.
            m.d.comb += self.o_wifi_gpio0.eq(self.i_btn[0])

            # Press btn0 to exit this bitstream.
            R_delay_reload = Signal(20, reset=0)
            with m.If(R_delay_reload[19] == 0):
                m.d.sync += R_delay_reload.eq(R_delay_reload + 1)
            m.d.comb += self.o_user_programn.eq((~self.i_btn[0])
                                                | (~R_delay_reload[19]))

            # Clock generator.
            m.domains.sync = cd_sync = ClockDomain("sync")
            m.domains.pixel = cd_pixel = ClockDomain("pixel")
            m.domains.shift = cd_shift = ClockDomain("shift")

            m.submodules.ecp5pll = pll = ECP5PLL()
            pll.register_clkin(clk_in, platform.default_clk_frequency)
            pll.create_clkout(cd_sync, platform.default_clk_frequency)
            pll.create_clkout(cd_pixel, pixel_f)
            pll.create_clkout(cd_shift,
                              pixel_f * 5.0 * (1.0 if self.ddr else 2.0))

            platform.add_clock_constraint(cd_sync.clk,
                                          platform.default_clk_frequency)
            platform.add_clock_constraint(cd_pixel.clk, pixel_f)
            platform.add_clock_constraint(
                cd_shift.clk, pixel_f * 5.0 * (1.0 if self.ddr else 2.0))

            # VGA signal generator.
            vga_r = Signal(8)
            vga_g = Signal(8)
            vga_b = Signal(8)
            vga_hsync = Signal()
            vga_vsync = Signal()
            vga_blank = Signal()

            m.submodules.vga = vga = VGA(
                resolution_x=self.timing.x,
                hsync_front_porch=hsync_front_porch,
                hsync_pulse=hsync_pulse_width,
                hsync_back_porch=hsync_back_porch,
                resolution_y=self.timing.y,
                vsync_front_porch=vsync_front_porch,
                vsync_pulse=vsync_pulse_width,
                vsync_back_porch=vsync_back_porch,
                bits_x=16,  # Play around with the sizes because sometimes
                bits_y=16  # a smaller/larger value will make it pass timing.
            )
            with m.If(vga.o_beam_y < 400):
                m.d.comb += [vga.i_r.eq(0xff), vga.i_g.eq(0), vga.i_b.eq(0)]
            with m.Else():
                m.d.comb += [vga.i_r.eq(0), vga.i_g.eq(0xff), vga.i_b.eq(0)]
            m.d.comb += [
                vga.i_clk_en.eq(1),
                vga.i_test_picture.eq(0),
                vga_r.eq(vga.o_vga_r),
                vga_g.eq(vga.o_vga_g),
                vga_b.eq(vga.o_vga_b),
                vga_hsync.eq(vga.o_vga_hsync),
                vga_vsync.eq(vga.o_vga_vsync),
                vga_blank.eq(vga.o_vga_blank),
            ]

            # VGA to digital video converter.
            tmds = [Signal(2) for i in range(4)]
            m.submodules.vga2dvid = vga2dvid = VGA2DVID(
                ddr=self.ddr, shift_clock_synchronizer=False)
            m.d.comb += [
                vga2dvid.i_red.eq(vga_r),
                vga2dvid.i_green.eq(vga_g),
                vga2dvid.i_blue.eq(vga_b),
                vga2dvid.i_hsync.eq(vga_hsync),
                vga2dvid.i_vsync.eq(vga_vsync),
                vga2dvid.i_blank.eq(vga_blank),
                tmds[3].eq(vga2dvid.o_clk),
                tmds[2].eq(vga2dvid.o_red),
                tmds[1].eq(vga2dvid.o_green),
                tmds[0].eq(vga2dvid.o_blue),
            ]

            # LED blinky
            counter_width = 28
            countblink = Signal(8)
            m.submodules.blink = blink = Blink(counter_width)
            m.d.comb += [
                countblink.eq(blink.o_led),
                self.o_led[6:8].eq(countblink[6:8]),
                self.o_led[0].eq(vga_vsync),
                self.o_led[1].eq(vga_hsync),
                self.o_led[2].eq(vga_blank),
            ]

            if (self.ddr):
                # Vendor specific DDR modules.
                # Convert SDR 2-bit input to DDR clocked 1-bit output (single-ended)
                # onboard GPDI.
                m.submodules.ddr0_clock = Instance("ODDRX1F",
                                                   i_SCLK=ClockSignal("shift"),
                                                   i_RST=0b0,
                                                   i_D0=tmds[3][0],
                                                   i_D1=tmds[3][1],
                                                   o_Q=self.o_gpdi_dp[3])
                m.submodules.ddr0_red = Instance("ODDRX1F",
                                                 i_SCLK=ClockSignal("shift"),
                                                 i_RST=0b0,
                                                 i_D0=tmds[2][0],
                                                 i_D1=tmds[2][1],
                                                 o_Q=self.o_gpdi_dp[2])
                m.submodules.ddr0_green = Instance("ODDRX1F",
                                                   i_SCLK=ClockSignal("shift"),
                                                   i_RST=0b0,
                                                   i_D0=tmds[1][0],
                                                   i_D1=tmds[1][1],
                                                   o_Q=self.o_gpdi_dp[1])
                m.submodules.ddr0_blue = Instance("ODDRX1F",
                                                  i_SCLK=ClockSignal("shift"),
                                                  i_RST=0b0,
                                                  i_D0=tmds[0][0],
                                                  i_D1=tmds[0][1],
                                                  o_Q=self.o_gpdi_dp[0])
            else:
                m.d.comb += [
                    self.o_gpdi_dp[3].eq(tmds[3][0]),
                    self.o_gpdi_dp[2].eq(tmds[2][0]),
                    self.o_gpdi_dp[1].eq(tmds[1][0]),
                    self.o_gpdi_dp[0].eq(tmds[0][0]),
                ]

        return m
Example #20
0
import ubinascii
import time
import machine

from blink import Blink
from temperature import TemperatureSensor
from temperature_client import TemperatureClient

client_id = ubinascii.hexlify(machine.unique_id())
sensor = TemperatureSensor(5)
led = Blink(16)
tc = TemperatureClient(client_id, '93.80.147.216', 5, topic='esp/temp')
while True:
    tc.publishTemperature()
    print(str(time.localtime()) + ' | temp: ' + str(sensor.read_temp()))
    led.blink(2, 0.2)
    time.sleep(60)
Example #21
0
 def _test_health(self):
     b = Blink()
     print b.health()
Example #22
0
 def test_homescreen(self):
     b = Blink()
     data = b.homescreen()
     self.assertTrue(data['account'] is not None)
Example #23
0

@app.route('/')
def index():
    return render_template('index.html')


@app.route('/find')
def find():
    json_dict = blink.find()
    if json_dict is not None:
        return jsonify(manufacturer=json_dict['bstick_man'],
                       description=json_dict['bstick_desc'],
                       serialNumber=json_dict['bstick_ser'],
                       color=json_dict['bstick_col'],
                       name=json_dict['bstick_name'],
                       info2=json_dict['bstick_info_2'])
    else:
        return '<Not Connected>'


@app.route('/blink')
def blink():
    rgb_list = blink.blink()
    return ','.join(str(i) for i in rgb_list)


if __name__ == '__main__':
    blink = Blink()
    app.run()
Example #24
0
 def test_events(self):
     b = Blink()
     b.connect()
     events = b.events(b.networks[0])
     self.assertEqual(type(events), list)
Example #25
0
 def test_cameras(self):
     b = Blink()
     b.connect()
     cameras = b.cameras(b.networks[0])
     self.assertEqual(type(cameras), list)
Example #26
0
 def test_download_video(self):
     b = Blink()
     b.connect()
     events = b.events(b.networks[0])
     event = events[0]
     b.download_video(event)
Example #27
0
class TestBlink(unittest.TestCase):
    email = ""
    password = ""

    def setUp(self):
        self.b = Blink(self.email, self.password)
        self.b.login()

###############################################################################
##  Highlighted Client APIs
###############################################################################

    def test_login(self):
        self.assertTrue(self.b.connected)

    def test_homescreen(self):
        data = self.b.homescreen()
        self.assertTrue(data['account'] is not None)
        self.assertTrue(data['network'] is not None)
        for device in data['devices']:
            if device['device_type'] is not None and device[
                    'device_type'] == "camera":
                content, filename = self.b.download_thumbnail_home_v2(device)
                blink.save_to_file(content, "home_" + filename)

    def test_events_v2(self):
        events = self.b.eventsv2()
        self.assertEqual(type(events), list)

    def test_video_count(self):
        count = self.b.get_video_count()
        print("video count = " + str(count))

    def test_events_v2_download(self):
        events = self.b.eventsv2()
        if len(events) == 0:
            return
        event = events[0]
        content = self.b.download_video_v2(event)
        filename = self.b.get_event_name_v2(event)
        blink.save_to_file(content, "event_" + filename)

    def test_thumbnail_event_v2_download(self):
        events = self.b.eventsv2()
        if len(events) == 0:
            return
        event = events[0]
        content = self.b.download_thumbnail_event_v2(event)
        filename = self.b.get_thumbnail_name_event(event, "event")
        f = open(filename, 'wb')
        f.write(content)
        f.close()
        print('Save downloaded image to ' + filename)

###############################################################################
##  Wrapped Functions
###############################################################################

    def test_list_network_ids(self):
        ids = self.b.list_network_ids()
        self.assertEqual(type(ids), list)

    def test_list_camera_ids(self):
        ids = self.b.list_camera_ids()
        self.assertEqual(type(ids), list)

    def test_events_from_camera(self):
        ids = self.b.list_camera_ids()
        if len(ids) > 0:
            id = ids[0]
            events = self.b.events_from_camera(id, 1)
            if len(events) > 0:
                event = events[0]
                content = self.b.download_video_v2(event)
                filename = self.b.get_event_name_v2(event)
                blink.save_to_file(content, "event_camera_" + filename)

    def test_refresh_all_cameras_thumbnail(self):
        self.b.refresh_all_cameras_thumbnail()
        data = self.b.homescreen()
        for device in data['devices']:
            if device['device_type'] is not None and device[
                    'device_type'] == "camera":
                content, filename = self.b.download_thumbnail_home_v2(device)
                filename = "test_refresh_" + filename
                blink.save_to_file(content, filename)
                print("Download latest thumbnails to " + filename)


###############################################################################
##  Other Client APIs
###############################################################################

    def test_cameras(self):
        cameras = self.b.cameras(self.b.networks[0])
        self.assertEqual(type(cameras), list)

    def test_clients(self):
        clients = self.b.clients()
        self.assertTrue(clients['clients'] is not None)
        print(clients)

    def test_sync_modules(self):
        sync_modules = self.b.sync_modules(self.b.networks[0])
        print(sync_modules)

    def test_regions(self):
        regions = self.b.regions()
        print(regions)

    def test_get_video_info(self):
        events = self.b.eventsv2()
        if len(events) == 0:
            return
        event = events[0]
        eventinfo = self.b.get_video_info(event.id)
        print("eventinfo:" + str(eventinfo))

    def test_delete_video(self):
        events = self.b.eventsv2(1000)
        if len(events) == 0:
            return
        event = events[len(events) - 1]
        suc = self.b.delete_video(event.id)
        self.assertTrue(suc)
Example #28
0
from umqtt.robust import MQTTClient