import json
import base64
import numpy as np
import matplotlib.pyplot as plt

def decode_and_plot_channel(json_path, target_channel=1, dtype=np.float32):
    with open(json_path, 'r', encoding='utf-8') as f:
        data = json.load(f)

    # Берём первый измерительный блок
    measurement = data[0]
    channels = measurement["channel_data"]

    # Ищем нужный канал
    for ch in channels:
        if ch["channel_num"] == target_channel:
            encoded = ch["channel_data"]
            raw_bytes = base64.b64decode(encoded)
            arr = np.frombuffer(raw_bytes, dtype=dtype)

            plt.plot(arr, label=f"Канал {target_channel}")
            plt.xlabel("Индекс")
            plt.ylabel("Амплитуда")
            plt.title(f"График сигнала из канала {target_channel}")
            plt.grid(True)
            plt.legend()
            plt.tight_layout()
            plt.show()
            return

    print(f"Канал с номером {target_channel} не найден.")


import json
import base64
import numpy as np
import scipy.fft as fft
import matplotlib.pyplot as plt

class DataDecoder:
    def __init__(self, filename):
        self.data = ''
        with open(filename, 'r') as file:
            self.data = file.read()
        self.structed_data = json.loads(self.data)

    def getRawData(self, averaging_num=0, data_num=0, channel_num=0):
        for items in self.structed_data:
            if(items['averaging_num'] == averaging_num and items['data_num'] == data_num):
                for channel_data in items['channel_data']:
                    if(channel_data['channel_num'] == channel_num):
                        return channel_data['channel_data']
        return None

    def getDataDecoded(self, averaging_num=0, data_num=0, channel_num=0, points=10):
        rawData = self.getRawData(averaging_num, data_num, channel_num)
        edata = base64.b64decode(rawData.encode('utf-8'))
        arr = np.frombuffer(edata, dtype=np.int16, count=points, offset=0)
        return arr

    def getDataScaled(self, averaging_num=0, data_num=0, channel_num=0, points=10, range=5.0):
        decodedData = self.getDataDecoded(averaging_num, data_num, channel_num, points)
        return range * decodedData / 32768

    def getDataRate(self, averaging_num=0, data_num=0):
        for items in self.structed_data:
            if(items['averaging_num'] == averaging_num and items['data_num'] == data_num):
                return items['measurement_rate']

    def getDataSpectrum(self, averaging_num=0, data_num=0, channel_num=0, points=10, range=5.0, zero_fill=0, first_idx=0, last_idx=10):
        scaledData = self.getDataScaled(averaging_num, data_num, channel_num, points, range)
        zerofilledData = np.append(scaledData[first_idx:last_idx], np.zeros(zero_fill))
        rate = self.getDataRate()
        transferedData = fft.rfft(zerofilledData) * 2 / (last_idx-first_idx)
        freqs = fft.rfftfreq((last_idx-first_idx)+zero_fill, 1/rate)
        spectrum = np.abs(transferedData)
        phases = np.angle(transferedData)
        spect_dict = {'freqs': freqs,
                      'phases': phases,
                      'spectrum': spectrum}
        return spect_dict

    def getDataPoints(self, averaging_num=0, data_num=0):
        for items in self.structed_data:
            if(items['averaging_num'] == averaging_num and items['data_num'] == data_num):
                return items['measurement_points']



def plot_signal_B(decoder, averaging_num=0, data_num=0, channel_num=1, range_volts=5.0):
    points = decoder.getDataPoints(averaging_num, data_num)[0]
    rate = decoder.getDataRate(averaging_num, data_num)
    signal = decoder.getDataScaled(averaging_num, data_num, channel_num, points, range_volts)

    time = np.arange(points) / rate
    plt.figure(figsize=(12, 4))
    plt.plot(time, signal, label=f'Канал {channel_num}')
    plt.xlabel('Время, с')
    plt.ylabel('Амплитуда, В')
    plt.title(f'Сигнал (Канал {channel_num})')
    plt.grid(True)
    plt.legend()
    plt.tight_layout()
    plt.show()
dec = DataDecoder('test.json')  # заменишь на нужное имя файла
plot_signal_B(dec)


