#!/usr/bin/env python3

import cv2
import banner_ivu_export
import numpy as np
from util import fprint

class qr_reader():
    camera = None
    def __init__(self, ip, port):
        self.camera = banner_ivu_export.DriveImg(ip, port)

    def read_qr(self, tries=1):
        print("Trying " + str(tries) + " frames.")
        for x in range(tries):
            try:
                imgtype, img = self.camera.read_img()
                #fprint(imgtype)
                image_array = np.frombuffer(img, np.uint8)
                img = cv2.imdecode(image_array, cv2.IMREAD_COLOR)
                #cv2.imshow('Image', img)
                #cv2.waitKey(1)
                detect = cv2.QRCodeDetector()
                value, points, straight_qrcode = detect.detectAndDecode(img)
                return value
            except:
                continue
        return False
        

class video_streamer():
    camera = None
    def __init__(self, ip, port):
        self.camera = banner_ivu_export.DriveImg(ip, port)

    def get_frame(self):
        try:
            return self.camera.read_img()
        except:
            return False

if __name__ == "__main__":
    test = qr_reader("192.168.1.125", 32200)
    while True:
        fprint(test.read_qr(5))