from smbus2 import SMBus
import pyqtgraph as pg
from pyqtgraph.Qt import QtCore, QtGui
import numpy as np
import sys
import time

# 定数
ADRS2040_ADDR=0x41
ADRS2040_CMD_INVALID      = 0
ADRS2040_CMD_ADC_START    = 1
ADRS2040_CMD_ADC_STOP     = 2
ADRS2040_CMD_SET_RATE     = 3
ADRS2040_CMD_GET_COUNT    = 4
ADRS2040_CMD_GET_VALUE    = 5

class ADCGraph:
    def __init__(self):
        self.win = pg.GraphicsWindow()
        self.win.setWindowTitle('ADC Input')
        self.plt = self.win.addPlot()
        self.plt.setYRange(0,1024)
        self.curve = self.plt.plot(pen=(0, 0, 255))
    
        
        self.data = np.zeros(100)
        #
        # 開始
        self.i2c = SMBus(1)
        self.i2c.write_word_data(ADRS2040_ADDR, ADRS2040_CMD_SET_RATE, 50)
        self.i2c.write_byte(ADRS2040_ADDR, ADRS2040_CMD_ADC_START)

        self.timer = QtCore.QTimer()
        self.timer.timeout.connect(self.update)
        self.timer.start(10)


    def update(self):
        nod = 0
        nod = self.i2c.read_word_data(ADRS2040_ADDR,ADRS2040_CMD_GET_COUNT )
        for i in range(nod):
            value = self.i2c.read_word_data(ADRS2040_ADDR,ADRS2040_CMD_GET_VALUE)
            # print(value)
            self.data = np.delete(self.data, 0)
            self.data = np.append(self.data, value)
        self.curve.setData(self.data)

if __name__ == "__main__":
    graphWin = ADCGraph()

    if (sys.flags.interactive != 1) or not hasattr(QtCore, 'PYQT_VERSION'):
        QtGui.QApplication.instance().exec_()