class CameraFeedScreen(BaseScreen):
    try:
        camera = PiCamera(resolution=(2240,1840))
    except:
        pass
    try:
        camera.exif_tags['IFD0.Artist']=str(config.get('operator', 0))
        camera.exif_tags['IFD0.ImageDescription']=str('PLOT: ' + str(config.get('plot_num', 0)) + ', HEIGHT: ' + str(config.get('height', 0)))
        camera.exif_tags['IFD0.Copyright'] = 'Copyright (c) 2019 BYU Crop Biomechanics Laboratory'
    except:
        pass # print('No Operator Data Added')

    def on_pre_enter(self):
        sensor = Sensor()
        sensor.clear_gps_memory()

    def on_enter(self):
        try:
            self.camera.start_preview(rotation=180,fullscreen=False,window=(230,10,560,460))
        except:
            pass # print('No Camera Found')
    def captureImage(self):
        try:
            def decdeg2dms(dd):
                dd = abs(dd)
                minutes,seconds = divmod(dd*3600,60)
                degrees,minutes = divmod(minutes,60)
                return (degrees,minutes,seconds)
            sensor = Sensor()
            sensor.get_header_data()
            sensor_data = sensor.get_sensor_data()
            location = [sensor_data["Location"][0], sensor_data["Location"][1]]
            latdms = decdeg2dms(location[0])
            londms = decdeg2dms(location[1])
        except:
            # print('Location Data not found')
            location = [0, 0]
        try:
            self.camera.exif_tags['GPS.GPSLatitudeRef'] = 'N' if location[0] > 0 else 'S'
            self.camera.exif_tags['GPS.GPSLongitudeRef'] = 'E' if location[1] > 0 else 'W'
            self.camera.exif_tags['GPS.GPSLatitude'] = '%d/1,%d/1,%d/100' % (latdms[0], latdms[1], latdms[2])
            self.camera.exif_tags['GPS.GPSLongitude'] = '%d/1,%d/1,%d/100' % (londms[0], londms[1], londms[2])
        except:
            pass # print('Location Data not added')
        try:
            dt = datetime.datetime.now()
            filename = 'Images/Stalk_' + dt.strftime('%Y_%m_%d_%H_%M_%S') + '.jpg'
            self.camera.capture(filename)
        except:
            pass # print('Taking Imaginary Picture')

    def on_leave(self):
        try:
            self.camera.stop_preview()
        except:
            pass
Пример #2
0
 def login(self):
     print('Trying to authorize at VK...')
     login_result = self.vkapi.log_in(
         configurator.get('VK_LOGIN'),
         configurator.get('VK_PASS'),
         configurator.get('VK_APP_ID'),
         'audio'
     )
     if login_result:
         print('VK auth succeeded!')
     else:
         print('VK auth failed.')
     self.last_login = time.time()
 def on_pre_enter(self):
     """Before the Screen loads, read the configuration file to get the current
     list of notes. Show the default buttons."""
     self.event = Clock.schedule_interval(self.update_time, ONE_SEC)
     self.height_num = str(config.get('height',0))
     self.plot = str(config.get('plot_num',0))
     self.operator = str(config.get('operator','N/A'))
     self.time = datetime.datetime.now().strftime("%I:%M:%S %p")
     # Get notes from config file
     notes = config.get('notes', {
         "pretest": [],
         "posttest": [],
         "bank": []
     })
     # Set the data
     self.ids['pretest'].list_data = notes["pretest"]
     self.ids['posttest'].list_data = notes["posttest"]
Пример #4
0
 def on_pre_leave(self):
     self.event.cancel()
     ts = TestSingleton()
     ts.clear_all()
     ts.set_height(str(config.get('height', "")))
     ts.set_plot(str(config.get('plot_num', "")))
     config.set('break_height', "N/A")
     #ts.set_pre_notes(str(config.get('height', "")))
     #ts.set_post_notes(str(config.get('height', "")))
     ts.set_operator(str(config.get('operator', "")))
     ts.set_timestamp(self.start_timestamp)
     ts.set_datasets(self.datasets)
     self.datasets = []
     self.graph1.remove_plot(self.plot1)
     self.graph1._clear_buffer()
     self.graph2.remove_plot(self.plot2)
     self.graph2._clear_buffer()
Пример #5
0
 def on_pre_enter(self):
     self.event = Clock.schedule_interval(self.update_data, ONE_SEC / 2)
     self.sensor = Sensor()
     self.config_data = config.get('sensors', {})
     if 'IMU Angle' in self.config_data:
         self.offset = self.config_data['IMU Angle']['offset']
     else:
         self.offset = 0
    def on_pre_enter(self):
        sensor = Sensor()
        sensor.clear_gps_memory()

        # Get notes from config file
        notes = config.get('notes', {"posttest": []})

        # Set the data
        self.ids['posttest'].list_data = notes["posttest"]
    def on_pre_enter(self):
        """Prior to the screen loading, check if barcode needs to be scanned"""
        use_barcode = config.get('barcode_scan', "OFF")

        barcode = self.ids['barcode']
        barcode.text = ""

        if use_barcode == "OFF":
            self.save_test()
            super(SaveScreen, self).move_to('testing_screen')
Пример #8
0
 def __init__(self):
     self.config_data = config.get('sensors', {})
     self.load = 0.0
     self.load_adc = 0.0
     try:
         self.slope = self.config_data['Y Load']['slope']
         self.intercept = self.config_data['Y Load']['intercept']
     except:
         self.slope = 1.0
         self.intercept = 0
 def set_sensor(self, name):
     self.sensor_name = name
     self.config_data = config.get('sensors', {})
     if name in self.config_data:
         self.points_list = self.config_data[name]['points_list']
         self.slope = self.config_data[name]['slope']
         self.intercept = self.config_data[name]['intercept']
     else:
         self.points_list = []
         self.slope = 1
         self.intercept = 0
Пример #10
0
    def run(self):
        try:
            gags = self.ng.get_latest_hot()[::-1]
            for gag in gags:
                match = db.select('SELECT * FROM gags WHERE gag="{}"'.format(
                    gag.id))
                if not match:
                    # New gag!
                    db.execute(
                        'INSERT INTO gags(gag, kind) VALUES("{}", "{}")'.
                        format(gag.id, gag.kind))

                    if gag.kind == 'image':
                        self.engine.telegram.sendPhoto(
                            chat_id=configurator.get('CHAT_ID'),
                            photo=gag.img['src'],
                            caption=gag.name)
                    elif gag.kind == 'gif':
                        import urllib2
                        from random import random
                        data = urllib2.urlopen(gag.animated['data-mp4']).read()
                        tmp = open(
                            '/tmp/{}.mp4'.format(str(int(random() * 1000000))),
                            'w+b')
                        tmp.write(data)
                        tmp.seek(0)

                        self.engine.telegram.sendVideo(
                            chat_id=configurator.get('CHAT_ID'),
                            video=tmp,
                            caption=gag.name)
                    elif gag.kind == 'article':
                        self.engine.telegram.sendPhoto(
                            chat_id=configurator.get('CHAT_ID'),
                            photo=gag.img['href'],
                            caption=u'Full version: {}'.format(gag.name))
            # print 'NineGagPoster.run()'
            self.start_later(3)
        except:
            traceback.print_exc()
            self.start_later(60)
Пример #11
0
    def run(self):
        try:
            gags = self.ng.get_latest_hot()[::-1]
            for gag in gags:
                match = db.select('SELECT * FROM gags WHERE gag="{}"'.format(gag.id))
                if not match:
                    # New gag!
                    db.execute('INSERT INTO gags(gag, kind) VALUES("{}", "{}")'.format(gag.id, gag.kind))

                    if gag.kind == 'image':
                        self.engine.telegram.sendPhoto(
                            chat_id=configurator.get('CHAT_ID'),
                            photo=gag.img['src'],
                            caption=gag.name
                        )
                    elif gag.kind == 'gif':
                        import urllib2
                        from random import random
                        data = urllib2.urlopen(gag.animated['data-mp4']).read()
                        tmp = open('/tmp/{}.mp4'.format(str(int(random() * 1000000))), 'w+b')
                        tmp.write(data)
                        tmp.seek(0)

                        self.engine.telegram.sendVideo(
                            chat_id=configurator.get('CHAT_ID'),
                            video=tmp,
                            caption=gag.name
                        )
                    elif gag.kind == 'article':
                        self.engine.telegram.sendPhoto(
                            chat_id=configurator.get('CHAT_ID'),
                            photo=gag.img['href'],
                            caption=u'Full version: {}'.format(gag.name)
                        )
            # print 'NineGagPoster.run()'
            self.start_later(3)
        except:
            traceback.print_exc()
            self.start_later(60)
Пример #12
0
    def subreddit(self, source, engine, message, cmd, args):
        engine.telegram.sendChatAction(message.chat_id, telegram.ChatAction.TYPING)
        client = ImgurClient(configurator.get('IMGUR_KEY'), configurator.get('IMGUR_SECRET'))

        gallery = client.subreddit_gallery(source, sort='new', window='all', page=int(random() * 30))
        gallery = filter(lambda item: hasattr(item, 'size') and item.size > 0, gallery)

        print(gallery)

        attempt = 0
        while attempt < 3:
            item = choice(gallery)

            engine.telegram.sendChatAction(message.chat_id, telegram.ChatAction.UPLOAD_PHOTO)

            print(message.chat_id)
            print(item.link)
            print(item.title)

            tf = NamedTemporaryFile(delete=False, suffix=item.link.split('.')[-1])
            img = urllib2.urlopen(item.link).read()
            tf.write(img)
            tf.close()

            try:
                engine.telegram.sendPhoto(
                    chat_id=message.chat_id,
                    photo=open(tf.name, 'r'),
                    # photo='https://www.google.com.ua/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png',
                    # caption=item.title
                )
                os.unlink(tf.name)
                return True
            except:
                os.unlink(tf.name)
                attempt += 1
        engine.telegram.sendMessage(chat_id=message.chat_id, text='Я тричі спробувала отримати картинку, але сталася якась помилка в API telegram :(')

        return True
    def on_pre_enter(self):
        """Before the Screen loads, read the configuration file to get the current
        list of notes. Show the default buttons."""

        # Get notes from config file
        notes = config.get('notes', {
            "pretest": [],
            "posttest": [],
            "bank": []
        })
        # Set the data
        self.ids['pretest'].list_data = notes["pretest"]
        self.ids['posttest'].list_data = notes["posttest"]
        self.ids['bank'].list_data = notes["bank"]

        # Add Buttons
        self.default_buttons()
    def save(self):
        notes = config.get('notes', {
            "pretest": [],
            "posttest": [],
            "bank": []
        })
        input = self.ids['note']

        note = input.text
        valid = input.validate()
        exists = (note in notes['pretest']) or (note in notes['posttest']) \
            or (note in notes['bank'])

        if valid and not exists:
            notes['bank'].append(input.text)
            config.set('notes', notes)
            return True
        else:
            input.show_invalid()
            input.focus = True
            return False
Пример #15
0
    def run(self):
        channels = ('DotaCinema', 'WronchiAnimation')

        for channel in channels:
            try:
                videos = self.yt.get_latest(channel)
                video = videos[0]

                last_video_id = get_var('youtube.{}.last_id'.format(channel),
                                        '')
                if video.id != last_video_id:
                    set_var('youtube.{}.last_id'.format(channel), video.id)
                    print 'New video: {}'.format(str(video))

                    self.engine.telegram.sendPhoto(
                        chat_id=configurator.get('CHAT_ID'),
                        photo=video.img,
                        caption=u'{}: {}'.format(video.name, video.url))

                # match = db.select('SELECT * FROM youtube WHERE id="{}"'.format(video.id))
            except:
                traceback.print_exc()

        self.start_later(60)
Пример #16
0
    def run(self):
        channels = ('DotaCinema', 'WronchiAnimation')

        for channel in channels:
            try:
                videos = self.yt.get_latest(channel)
                video = videos[0]

                last_video_id = get_var('youtube.{}.last_id'.format(channel), '')
                if video.id != last_video_id:
                    set_var('youtube.{}.last_id'.format(channel), video.id)
                    print 'New video: {}'.format(str(video))

                    self.engine.telegram.sendPhoto(
                        chat_id=configurator.get('CHAT_ID'),
                        photo=video.img,
                        caption=u'{}: {}'.format(video.name, video.url)
                    )

                # match = db.select('SELECT * FROM youtube WHERE id="{}"'.format(video.id))
            except:
                traceback.print_exc()

        self.start_later(60)
Пример #17
0
 def on_pre_enter(self):
     """Before the Screen loads, read the configuration file to get the current
     operator and set the TextInput text."""
     input = self.ids['operator']
     input.text = str(config.get('operator', "Default User"))
     input.validate()
 def on_pre_enter(self):
     """Before the Screen loads, read the configuration file to get the current
     height."""
     input = self.ids['height']
     input.text = str(config.get('height', 0))
     input.validate()
Пример #19
0
 def __init__(self):
     self.telegram = telegram.Bot(token=configurator.get('TOKEN'))
     self.initial = True
     self.id = 0
     self.handlers = []
     self.terminated = False
Пример #20
0
 def on_pre_enter(self):
     """Before the Screen loads, read the configuration file to get the current
     list of notes. Show the default buttons."""
     self.height_num = str(config.get('height', 0))
     self.plot = str(config.get('plot_num', 0))
     self.operator = str(config.get('operator', 'N/A'))
Пример #21
0
 def on_pre_enter(self):
     """Before the Screen loads, read the configuration file to get the current
     plot number."""
     input = self.ids['plot_num']
     input.text = str(config.get('plot_num', 1))
     input.validate()
Пример #22
0
 def __init__(self):
     self.telegram = telegram.Bot(token=configurator.get('TOKEN'))
     self.initial = True
     self.id = 0
     self.handlers = []
     self.terminated = False
Пример #23
0
 def __init__(self):
     self.config_data = config.get('sensors', {})
     try:
         self.offset = self.config_data['IMU Angle']['offset']
     except:
         self.offset = 0
Пример #24
0
 def request(self, command, data=None):
     request = urllib2.Request('http://dun.ai:8075/ServerAdmin/{}'.format(command), urllib.urlencode(data) if data else None)
     request.add_header('Authorization', 'Basic {}'.format(b64encode('{}:{}'.format(configurator.get('UT_ADMIN_LOGIN'), configurator.get('UT_ADMIN_PASSWORD')))))
     response = urllib2.urlopen(request)
     return BeautifulSoup(response.read(), 'lxml')
Пример #25
0
 def handle_say_admin(self, engine, message, cmd, args):
     engine.telegram.sendMessage(
         chat_id=configurator.get('CHAT_ID'),
         text=args
     )
Пример #26
0
    def handle_inline(self, engine, inline_query):
        text = inline_query.query
        # parts = filter(None, message.text.split(' '))
        # if len(parts) < 3:
        #     engine.telegram.sendMessage(
        #         text='Інструкція:\n/gen image_name Текст для відображення.\nДоступні зображення:\n{}'.format(
        #             '\n'.join('{}'.format('.'.join(x.split('.')[:-1])) for x in os.listdir('./memes'))
        #         ),
        #         chat_id=message.chat_id,
        #         reply_to_message=message.message_id,
        #         reply_markup=telegram.ReplyKeyboardHide(
        #             selective=True
        #         )
        #     )
        #     return

        URL = 'http://cs4739v4.vk.me/u1843971/audios/f4201aa0226b.mp3?extra=LCwf3s2KXKBogyul0zl4g7NqOc68x4Gt9xqPmHCsFltcZ-GRKm0xBaQPS6SmERwJkZoG6mfcU-_Dkn7ArSIWg-O2wRFt_ndr4HQisQ3MDZszL1RzdJGQ8m80kLfMLbNQNHf3qY2VSTsQ'

        engine.telegram.answerInlineQuery(inline_query.id, [
            InlineQueryResultAudio(long(time.time() * 1000000), URL, 'audio/mp3', 'Test', 'Song123!')
        ])
        return

        parts = text.split(' ')

        if len(parts) < 2:
            engine.telegram.answerInlineQuery(inline_query.id, [
                InlineQueryResultArticle(long(time.time() * 1000000), 'Можливий варіант: ' + '.'.join(x.split('.')[:-1]), ':/')
                for x
                in os.listdir('./memes')
            ])
            return True

        name = parts[0]
        texts = filter(None, [x.strip() for x in ' '.join(parts[1:]).split(';')])
        try:
            meta_file = open('./memes/{}.json'.format(name))
            meta = json.loads(meta_file.read())
            meta_file.close()
        except:
            engine.telegram.answerInlineQuery(inline_query.id, [
                InlineQueryResultArticle(long(time.time() * 1000000), 'Зображення "{}" не знайдено :('.format(name), ':/')
                ])
            return

        img = Image.open(meta['src'])
        draw = ImageDraw.Draw(img)
        text_color = meta['textColor']
        font_size = meta['fontSize']
        iw, ih = img.size

        font = ImageFont.truetype('./fonts/Roboto-Regular.ttf', size=font_size)
        # font = ImageFont.load('./fonts/Roboto-Regular.ttf')

        rects = meta['rects']

        for i, text in enumerate(texts):
            try:
                x, y, w, h = rects[i]
            except:
                continue

            avg_width = draw.textsize(text, font)[0] / len(text)

            chars_per_line = w / avg_width

            multiline = '\n'.join(textwrap.wrap(text, width=chars_per_line))

            mw, mh = draw.multiline_textsize(multiline, font)

            draw.multiline_text((x + w / 2 - mw / 2, y + h / 2 - mh / 2), multiline, fill=text_color, font=font, align='center')

        # img.show()

        # img.drawText()

        # tf = NamedTemporaryFile(delete=False, suffix='.jpg')
        # img.save(tf, format='JPEG', quality=92)
        # tf.close()
        #
        # f = open(tf.name, 'rb')

        s = str(long(time.time() * 1000000))

        img_name_full = '{}.jpeg'.format(s)
        img_name_thumb = '{}_thumb.jpeg'.format(s)

        img_path_full = configurator.get('IMG_DIR') + img_name_full
        img_path_thumb = configurator.get('IMG_DIR') + img_name_thumb

        img.save(img_path_full)
        img.thumbnail((160, 160), Image.LINEAR)
        img.save(img_path_thumb)

        # engine.telegram.sendPhoto(
        #     chat_id=message.chat.id,
        #     photo=f
        # )

        # print(dict(
        #     photo_url=configurator.get('IMG_HOST') + img_name_full,
        #     thumb_url=configurator.get('IMG_HOST') + img_name_thumb,
        # ))

        engine.telegram.answerInlineQuery(inline_query.id, [
            InlineQueryResultPhoto(
                long(time.time() * 1000000),
                photo_url=configurator.get('IMG_HOST') + img_name_full,
                thumb_url=configurator.get('IMG_HOST') + img_name_thumb,
                photo_width=iw,
                photo_height=ih
            )
        ])

        # os.unlink(tf.name)

        return True
    def save_test(self):
        """Save all test data to csv file"""
        barcode = self.ids['barcode']

        ts = TestSingleton()
        self.datasets = ts.get_datasets()
        ts.set_break_height(str(config.get('break_height', 0)))

        #Prepare the notes
        notes = config.get('notes', {"pretest": [], "bank": []})
        pre_notes = notes["pretest"]
        post_notes = ts.get_post_notes()
        dt = datetime.datetime.now()

        # Sets the filename to save the csv file as
        config.set('curr_test_num', (config.get('curr_test_num', 0) + 1))
        filename = 'Tests/' + dt.strftime('%Y_%m_%d_%H_%M_%S') + '_P' + str(config.get('plot_num', 0)) \
            + '_T' + str(config.get('curr_test_num', 0)).zfill(2) + '.csv'

        try:
            gps.update()
        except:
            pass
        sensor = Sensor()
        sensor.get_header_data()
        sensor_data = sensor.get_sensor_data()
        temperature = str(sensor_data["Temperature"])
        humidity = str(sensor_data["Humidity"])
        location = [
            str("%.7f" % sensor_data["Location"][0]),
            str("%.7f" % sensor_data["Location"][1])
        ]

        self.config_data = config.get('sensors', {})
        self.NAMES = [
            'X Load', 'Y Load', 'IMU Angle', 'Pot Angle', 'Temperature',
            'Humidity'
        ]
        self.SENSOR = ['LOAD_X', 'LOAD_Y', 'IMU', 'POT', 'TEMP', 'HUM']
        self.UNITS = ['Pounds', 'Pounds', 'Deg', 'Deg', 'C', '%']
        self.IDS = ['loadx1', 'loady1', 'imu1', 'pot1', 'temp1', 'hum1']

        with open(filename, 'w+', newline='') as csvFile:
            writer = csv.writer(csvFile)
            writer.writerow(['----------META DATA----------'])
            writer.writerow(['SOFTWARE VERSION', '2.3.0'])
            writer.writerow(
                ['DEVICE OPERATOR',
                 str(config.get('operator', 0))])
            writer.writerow(['----------TEST ATTRIBUTES----------'])
            writer.writerow(['FIELD', 'VALUE', 'UNIT'])
            writer.writerow(['YEAR', dt.strftime("%Y")])
            writer.writerow(['MONTH', dt.strftime("%m")])
            writer.writerow(['DAY', dt.strftime("%d")])
            writer.writerow(
                ['TIME', dt.strftime("%H:%M:%S"), 'Local Time Zone'])
            writer.writerow(['PLOT', str(config.get('plot_num', 0)), '#'])
            writer.writerow(['HEIGHT', str(config.get('height', 0)), 'cm'])
            writer.writerow(['BARCODE', str(barcode.text)])
            writer.writerow(['TEMPERATURE', temperature, 'C'])
            writer.writerow(['HUMIDITY', humidity, '%'])
            writer.writerow(['LATITUDE', location[0], 'angular degrees'])
            writer.writerow(['LONGITUDE', location[1], 'angular degrees'])
            writer.writerow(['----------OPTIONAL DATA----------'])
            for i in range(5):
                try:
                    writer.writerow(
                        ['PRE_TEST_NOTE_' + str(i + 1), pre_notes[i]])
                except:
                    writer.writerow(['PRE_TEST_NOTE_' + str(i + 1), ''])
            for i in range(5):
                try:
                    writer.writerow(
                        ['POST_TEST_NOTE_' + str(i + 1), post_notes[i]])
                except:
                    writer.writerow(['POST_TEST_NOTE_' + str(i + 1), ''])
            writer.writerow(
                ['BREAK_HEIGHT',
                 str(config.get('break_height', 0)), 'cm'])
            writer.writerow(['LCA_WEIGTH', '0', 'g'])
            writer.writerow([
                '----------SENSOR CALIBRATION DATA (stored_value*A + B = raw_data)------'
            ])
            writer.writerow(['SENSOR', 'A', 'B', 'UNIT', 'ID'])
            for j in range(len(self.NAMES)):
                try:
                    writer.writerow([
                        self.SENSOR[j],
                        self.config_data[self.NAMES[j]]['slope'],
                        self.config_data[self.NAMES[j]]['intercept'],
                        self.UNITS[j], self.IDS[j]
                    ])
                except:
                    writer.writerow(
                        [self.SENSOR[j], '1', '0', self.UNITS[j], self.IDS[j]])
            writer.writerow(['----------TEST DATA-----------'])
            writer.writerow([
                'TIME (milliseconds)', 'ANGLE_POT', 'ANGLE_IMU', 'LOAD_X',
                'LOAD_Y'
            ])
            datasets = ts.get_datasets()
            for ds in datasets:
                writer.writerow([(ds.timestamp * 1000), ds.pot_angle,
                                 ds.imu_angle, ds.x_load, ds.y_load])

        csvFile.close()