import serial
import time
import re

import src.archive


def init_devs(dev_name=None, boud=115200, timeout=0.1):
    """:returns pointer to serial device"""
    if not dev_name:
        try:
            return serial.Serial('/dev/ttyACM0', boud, timeout=timeout)
        except:
            return serial.Serial('/dev/ttyACM1', boud, timeout=timeout)
    else:
        return serial.Serial(dev_name, boud, timeout=timeout)


def request_value(device, value):
    """requests voltage or current or real power or imag power or dummy response over serial connection
    :param device: pointer to serial device
    :param value: u -> voltage, i -> current, p -> real power, q -> imag power, x -> test response
    :returns measured value"""
    device.write(bytes(value, 'utf-8'))
    time.sleep(0.001)
    data = device.readline()
    if data:
        return data
    else:
        return None


def request_data(device):
    """:returns a single Data Point"""
    regex = r'([0-9]+\.[0-9]+),\s([0-9]+\.[0-9]+);\s([0-9]+\.[0-9]+),\s([0-9]+\.[0-9]+),\s([0-9]+\.[0-9]+)\\n'
    line = str(device.readline())
    while line == 'b\'\'':
        line = str(device.readline())
    data = re.findall(regex, line)
    if data:
        return src.archive.DataPoint(data[0][0], data[0][1], data[0][2], data[0][3], data[0][4])
    else:
        return None
