# -*- coding: utf-8 -*-
import serial
import time
import struct

class TA612CDevice:
    def __init__(self, port='/dev/ttyUSB0', baud_rate=9600):
        self.port = port
        self.baud_rate = baud_rate
        self.serial_connection = None

    def connect(self):
        """Establish a serial connection to the device."""
        self.serial_connection = serial.Serial(self.port, self.baud_rate, timeout=5)
        time.sleep(0.5)  # Reduced sleep time for connection establishment

    def start_real_time_sending(self):
        """Send command to start real-time data sending."""
        if self.serial_connection is None:
            raise Exception("Device not connected. Call connect() first.")

        # Construct the command frame
        header = 0x55AA  # Header
        command = 0x01   # Command to start real-time sending
        frame_length = 0x03  # Frame length (3 bytes for the command and length)
        sum_value = 0x03  # Correct sum value

        # Pack the command frame
        command_frame = struct.pack('<H B B B', header, command, frame_length, sum_value)

        self.serial_connection.write(command_frame)
        time.sleep(0.5)  # Reduced sleep time for device processing

        # Check for response
        if self.serial_connection.in_waiting >= 13:  # Expecting 13 bytes for the full response
            line = self.serial_connection.read(13)
            # print("Raw data received: {}".format(line))  # Debugging line

            # Extract the temperature data from the response
            # Assuming temperature data starts at index 4 and is 8 bytes long (4 channels)
            temperature_data = line[4:12]  # Adjust indices based on actual data structure
            # print("Extracted temperature data: {}".format(temperature_data))  # Debugging line

            # Unpack the received temperature data as 16-bit integers
            try:
                temperatures = struct.unpack('<HHHH', temperature_data)  # Assuming 4 channels of 16-bit data
                # print("Unpacked temperatures (raw): {}".format(temperatures))  # Debugging line
                
                # Convert raw temperature values to Celsius
                temperatures_celsius = [(temp / 10.0) for temp in temperatures]  # Divide by 10 to get the correct Celsius value
                
                # Format temperatures for output as a comma-separated string
                formatted_temperatures = ["{:.1f}".format(temp) for temp in temperatures_celsius]
                output = ",".join(formatted_temperatures)
                print(output)  # Print the output in the desired format
            except struct.error as e:
                print("Error unpacking data: {}".format(e))
        else:
            print("No data available")
            print("Bytes waiting: {}".format(self.serial_connection.in_waiting))

    def close(self):
        """Close the serial connection."""
        if self.serial_connection is not None:
            self.serial_connection.close()

if __name__ == "__main__":
    device = TA612CDevice(port='/dev/ttyUSB0')
    try:
        device.connect()
        device.start_real_time_sending()  # Start real-time data sending
    except KeyboardInterrupt:
        print("Program stopped.")
    finally:
        device.close()
