blockpy-edu / blockpy

Blockly that's more Python than JavaScript, powered with Skulpt
Apache License 2.0
398 stars 133 forks source link

please help me to solve, IndexError: list index out of range receiving data serial from xbee #38

Closed nurferyzulfadri closed 6 years ago

nurferyzulfadri commented 6 years ago

error

Traceback (most recent call last): File "./xbeetestmysql4.py", line 364, in OnTimer2 drawHum1(self,self.datacount,self.dataArray[0],SATUAN_HUM_UDARA,self.updatetimedb) IndexError: list index out of range

the script

import wx import os

from xbee import XBee,ZigBee import time import datetime from time import strftime import numpy as np import matplotlib matplotlib.use("WXAgg") from matplotlib.figure import Figure from matplotlib.backends.backend_wxagg import FigureCanvasWxAgg as FigCanvas from matplotlib.backends.backend_wxagg import NavigationToolbar2WxAgg as NavigationToolbar from matplotlib.ticker import MultipleLocator, FuncFormatter import pylab from matplotlib import pyplot import MySQLdb import MySQLdb as mdb import sys, argparse, logging import csv import serial import matplotlib.pyplot as plt

ID_TIMER = 1 ID_TIMER2 = 2 ID_TIMER3 = 3 SATUAN_HUM_UDARA = '%RH' SATUAN_HUM_TANAH = '%RH' SATUAN_INT_CAHAYA = 'lx' db = MySQLdb.connect("localhost", "root", "raspberry", "sensor") cur = db.cursor() dbreadsensor=[] DBtime=0 currenttime=0

serial

arduino = serial.Serial('/dev/ttyUSB0',9600)

def readsensor():

data = arduino.read()

if(data=='A'):

data = arduino.readline()

pieces = data.split('#')

kelembapanUdara = pieces[0]

kelembapanTanah = pieces[1]

intensitasCahaya = pieces[3]

print pieces[0]

def saveDB(hum1,hum2,intCahaya): datetimeWrite=(time.strftime("%Y-%m-%d ")+time.strftime("%H:%M:%S")) dateupdate=datetimeWrite sql = (""" INSERT INTO datasensor VALUES (%s,%s,%s,%s)""",(datetimeWrite,kelembapanUdara,kelembapanTanah,intensitasCahaya)) try: cur.execute(*sql) db.commit() except: print 'Error'

def drawHum1(self,x,update,satuan,updatetime): self.arrxTEMP.append(x) self.arryTEMP.append(update) self.MPL1.cla()

self.MPL1.ylim(0,15)

    self.MPL1.plot(self.arrxTEMP,self.arryTEMP,'--*g')
    self.MPL1.title_MPL("Hum Udara")
    self.MPL1.ylabel(SATUAN_HUM_UDARA)
    self.MPL1.ShowUpdate(update,'%',updatetime)
    self.MPL1.grid()
    self.MPL1.UpdatePlot()

def drawHum2(self,x,update,satuan,updatetime1): self.arrxHUM.append(x) self.arryHUM.append(update) self.MPL2.cla() self.MPL2.ylim(0,100) self.MPL2.plot(self.arrxHUM,self.arryHUM,':^b') self.MPL2.title_MPL("Hum Tanah") self.MPL2.ylabel(SATUAN_HUM_TANAH) self.MPL2.ShowUpdate(update,'%',updatetime1) self.MPL2.grid() self.MPL2.UpdatePlot()

def drawIntCahaya(self,x,update,satuan,updatetime2): self.arrxHUM.append(x) self.arryHUM.append(update) self.MPL2.cla() self.MPL2.ylim(0,100) self.MPL2.plot(self.arrxHUM,self.arryHUM,':^b') self.MPL2.title_MPL("Intensitas Cahaya") self.MPL2.ylabel(SATUAN_INT_CAHAYA) self.MPL2.ShowUpdate(update,'lx',updatetime2) self.MPL2.grid() self.MPL2.UpdatePlot()

class MatplotPanel(wx.Panel): def init(self,parent): wx.Panel.init(self,parent=parent, id=-1) font2 = wx.SystemSettings_GetFont(wx.SYS_SYSTEM_FONT) font2.SetPointSize(12) font3 = wx.SystemSettings_GetFont(wx.SYS_SYSTEM_FONT) font3.SetPointSize(25)

    self.dpi = 100
    self.Figure = Figure((1.0, 2.0), dpi=self.dpi)

    self.axes = self.Figure.add_axes([0.1,0.1,0.8,0.8])
    self.FigureCanvas = FigCanvas(self,-1,self.Figure)

    self.toolbar = NavigationToolbar(self.FigureCanvas)

    self.hboxmat = wx.BoxSizer(wx.HORIZONTAL)
    self.StaticText = wx.StaticText(self,-1,label='Last Update')
    self.StaticText.SetFont(font2)
    self.updatetime = wx.StaticText(self,-1,label='[ 00:00:00 ]:')
    self.updatetime.SetFont(font2)
    self.update = wx.StaticText(self,-1,label='   0.00')
    self.update.SetFont(font3)
    self.satuan = wx.StaticText(self,-1,label='    ')
    self.satuan.SetFont(font2)
    self.hboxmat.Add(self.StaticText,proportion =0, border = 2,flag=wx.TOP)
    self.hboxmat.Add(self.updatetime,proportion =0, border = 5,flag=wx.TOP)
    self.hboxmat.Add(self.update,proportion =0, border = 5,flag=wx.BOTTOM)
    self.hboxmat.Add(self.satuan,proportion =0, border = 5,flag=wx.TOP)

    self.vboxmat = wx.BoxSizer(wx.VERTICAL)
    self.vboxmat.Add(self.hboxmat, proportion =0)
    self.vboxmat.Add(self.FigureCanvas, proportion =1, flag=wx.LEFT | wx.TOP | wx.EXPAND)
    self.vboxmat.Add(self.toolbar, proportion =0, flag=wx.EXPAND)
    self.vboxmat.AddSpacer(10)     

    self.SetSizer(self.vboxmat)

def UpdatePlot(self):
    self.FigureCanvas.draw()

def plot(self,*args,**kwargs):
    self.axes.plot(*args,**kwargs)
    self.UpdatePlot()

def semilogx(self,*args,**kwargs):
    self.axes.semilogx(*args,**kwargs)
    self.UpdatePlot()

def semilogy(self,*args,**kwargs):
    self.axes.semilogy(*args,**kwargs)
    self.UpdatePlot()

def loglog(self,*args,**kwargs):
    self.axes.loglog(*args,**kwargs)
    self.UpdatePlot()

def grid(self,flag=True):
    if flag:
        self.axes.grid()
    else:
        self.axes.grid(False)

def title_MPL(self,TitleString="Mini Weather Station"):
    self.axes.set_title(TitleString)

def xlabel(self,XabelString="X"):
    self.axes.set_xlabel(XabelString)

def ylabel(self,YabelString="Y"):
    self.axes.set_ylabel(YabelString)

def xticker(self,major_ticker=1.0,minor_ticker=0.1):
    self.axes.xaxis.set_major_locator( MultipleLocator(major_ticker) )
    self.axes.xaxis.set_minor_locator( MultipleLocator(minor_ticker) )

def yticker(self,major_ticker=1.0,minor_ticker=0.1):
    self.axes.yaxis.set_major_locator( MultipleLocator(major_ticker) )
    self.axes.yaxis.set_minor_locator( MultipleLocator(minor_ticker) )

def legend(self,*args,**kwargs):
    self.axes.legend(*args,**kwargs)

def xlim(self,x_min,x_max):
    self.axes.set_xlim(x_min,x_max)

def ylim(self,y_min,y_max):
    self.axes.set_ylim(y_min,y_max)

def savefig(self,*args,**kwargs):
    self.Figure.savefig(*args,**kwargs)

def cla(self):
    self.axes.clear()
    self.Figure.set_canvas(self.FigureCanvas)
    self.UpdatePlot()

def ShowUpdate(self,update,satuan,updatetime):
    self.updatetime.SetLabel('[ '+updatetime+' ]:')
    self.update.SetLabel(update)
    self.satuan.SetLabel(satuan)

class WQMP2ET(wx.Frame):

def __init__(self, parent, title):
    super(WQMP2ET,self).__init__(parent, title=title,size=(1024,900))

    self.create_menu()
    self.create_status_bar()
    self.InitUI()
    self.Centre()
    #array data
    self.arrxHUM=[]
    self.arryHUM=[]
    self.arrxTEMP=[]
    self.arryTEMP=[]
    self.datacount=0 
    self.x=0      
    self.dataArray=[]
    self.tandaDO='A'
    self.tandabuff='A'
    self.updatetimedb = time.strftime("%H:%M:%S")

    #timer1 for time and date
    self.timer1 = wx.Timer(self, ID_TIMER)
    self.Bind(wx.EVT_TIMER, self.OnTimer1, id=ID_TIMER)
    self.timer1.Start(1000) #1000ms       
    t = time.localtime(time.time())
    st = time.strftime("%H:%M:%S", t) 
    #update log
    self.update_log('['+st+'] System Up')
    #system up  
    self.Show()

    #timer2 for update DB
    self.timer2 = wx.Timer(self, ID_TIMER2)
    self.Bind(wx.EVT_TIMER, self.OnTimer2, id=ID_TIMER2)
    self.timer2.Start(5*1000)
    #self.timer2.Start(int(self.inintervaldb.GetValue())*60*1000) #60*1000ms        
    t2 = time.localtime(time.time())
    st2 = time.strftime("%H:%M:%S", t2)

    #system up  
    self.Show()

def create_menu(self):
    self.menubar = wx.MenuBar()

    menu_file = wx.Menu()
    m_exit = menu_file.Append(-1, "E&xit\tCtrl-X", "Exit")
    self.Bind(wx.EVT_MENU, self.on_exit, m_exit)

    menu_help = wx.Menu()
    m_about = menu_help.Append(-1, "&About\tF1", "About the demo")
    self.Bind(wx.EVT_MENU, self.on_about, m_about)

    self.menubar.Append(menu_file, "&File")
    self.menubar.Append(menu_help, "&Help")
    self.SetMenuBar(self.menubar)

def create_status_bar(self):
    self.statusbar = self.CreateStatusBar(4)
    self.SetStatusWidths([-1, -1, -1, 175])

def InitUI(self):
    font = wx.SystemSettings_GetFont(wx.SYS_SYSTEM_FONT)
    font.SetPointSize(12)

    self.mainvbox = wx.BoxSizer(wx.HORIZONTAL)
    self.BoxSizer=wx.BoxSizer(wx.VERTICAL)
    self.BoxSizer2=wx.BoxSizer(wx.VERTICAL)

    self.MPL1 = MatplotPanel(self)
    self.MPL1.title_MPL("Kelembapan Udara")
    self.MPL1.ylabel(SATUAN_HUM_UDARA)
    self.BoxSizer.Add(self.MPL1,proportion =-1, border = 2,flag = wx.ALL | wx.EXPAND)

    self.MPL2 = MatplotPanel(self)
    self.MPL2.title_MPL("Kelembapan Tanah")
    self.MPL2.ylabel(SATUAN_HUM_TANAH)
    self.BoxSizer.Add(self.MPL2,proportion =-1, border = 2,flag = wx.ALL | wx.EXPAND)

    self.mainvbox.Add(self.BoxSizer,proportion =-1, border = 2,flag = wx.ALL | wx.EXPAND)

    #add test button
    self.BoxSizer3=wx.BoxSizer(wx.VERTICAL)
    self.RightPanel = wx.Panel(self,-1)
    self.BoxSizer3.Add(self.RightPanel,proportion =0, border = 5,flag = wx.ALL | wx.EXPAND)

    self.loglabel = wx.StaticText(self, label='LOG')
    self.loglabel.SetFont(font)
    self.logtext = wx.TextCtrl(self,size=(100,250),style=wx.TE_MULTILINE,)
    self.BoxSizer3.Add(self.loglabel,proportion =0, border = 5,flag = wx.ALL | wx.EXPAND)
    self.BoxSizer3.Add(self.logtext,proportion =0, border = 5,flag = wx.ALL | wx.EXPAND)

    self.mainvbox.Add(self.BoxSizer3,proportion =0, border = 2,flag = wx.ALL | wx.EXPAND)

    self.SetSizer(self.mainvbox)

    self.FlexGridSizer=wx.FlexGridSizer( rows=8, cols=2, vgap=5,hgap=5)
    self.FlexGridSizer.SetFlexibleDirection(wx.BOTH)

    textsetting = wx.StaticText(self.RightPanel, label='Settings')
    textsetting.SetFont(font)
    textsetting2 = wx.StaticText(self.RightPanel, label='')
    textsetting2.SetFont(font)
    self.FlexGridSizer.Add(textsetting,proportion =0, border = 2,flag = wx.ALL | wx.EXPAND)
    self.FlexGridSizer.Add(textsetting2,proportion =0, border = 2,flag = wx.ALL | wx.EXPAND)

    #datepicker
    textsettingd = wx.StaticText(self.RightPanel, label='Save DB to CSV File')
    textsettingd.SetFont(font)
    textsetting2d = wx.StaticText(self.RightPanel, label='')
    textsetting2d.SetFont(font)
    self.buttonsave = wx.Button(self.RightPanel,-1,"Save")
    self.buttonsave.Bind(wx.EVT_BUTTON,self.ButtonsaveEvent)
    self.datepicker = wx.DatePickerCtrl(parent=self.RightPanel,id=wx.ID_ANY)
    self.FlexGridSizer.Add(textsettingd,proportion =0, border = 2,flag = wx.ALL | wx.EXPAND)
    self.FlexGridSizer.Add(textsetting2d,proportion =0, border = 2,flag = wx.ALL | wx.EXPAND)
    self.FlexGridSizer.Add(self.datepicker,proportion =0, border = 2,flag = wx.ALL | wx.EXPAND)
    self.FlexGridSizer.Add(self.buttonsave,proportion =0, border = 2,flag = wx.ALL | wx.EXPAND)

    self.RightPanel.SetSizer(self.FlexGridSizer)

    self.Centre(wx.BOTH)
    self.Bind(wx.EVT_CLOSE, self.OnCloseWindow)

def OnTimer1(self, event):
    datetimeWrite=(time.strftime("%d-%b-%y ")+time.strftime("%H:%M:%S"))
    self.statusbar.SetStatusText(datetimeWrite, 3)
    self.statusbar.Refresh()
    if (time.strftime("%H:%M:%S")<'00:15:10' and self.tandabuff=='B'):
        self.tandabuff='A'
    if (time.strftime("%H:%M:%S")>'00:15:10' and self.tandabuff=='A'):
        self.arrxHUM=[]
        self.arryHUM=[]
        self.arrxTEMP=[]
        self.arryTEMP=[]
        self.tandabuff='B'
        self.update_log('['+time.strftime("%H:%M:%S")+'] Clear Buffer!!')

def OnTimer2(self, event):
    #st2 = time.strftime('%H:%M:%S')
    #self.x = self.x+1
    #dataArray = data.split('#')
    #drawHum1(self,dataArray[0],st2)
    #drawHum2(self,dataArray[1],st2)
    self.updatetimedb=time.strftime("%H:%M:%S")
    data_sensor = arduino.read()
    if(data_sensor=='A'):
     data_sensor = arduino.readline()
     self.dataArray = data_sensor.split('#')
    self.datacount=self.datacount+1
    **drawHum1(self,self.datacount,self.dataArray[0],SATUAN_HUM_UDARA,self.updatetimedb)**

def ButtonsaveEvent(self,event):
    self.datevalue = self.datepicker.GetValue().Format('%Y-%m-%d')
    file_choices = "CSV (*.csv)|*.csv"

    dlg = wx.FileDialog(
        self, 
        message="Save data as...",
        defaultDir=os.getcwd(),
        defaultFile=self.datevalue+".csv",
        wildcard=file_choices,
        style=wx.SAVE)

    if dlg.ShowModal() == wx.ID_OK:
        path = dlg.GetPath()
        filename=open(path,'wb')
        c=csv.writer(filename)
        c.writerow(['Tanggal-Jam','Temperature(degree C)','Humidity(%RH)'])
        #get data from database
        sql = ("""SELECT * FROM data sensor WHERE DATE(tanggal)=DATE(%s)""",(self.datevalue))
        try:
                cur.execute(*sql)
                rows = cur.fetchall()
                for row in rows:
                    c.writerow([row[0],row[1],row[2]])
                self.update_log('['+time.strftime("%H:%M:%S")+'] CSV Success !!')

        except:
               self.update_log('['+time.strftime("%H:%M:%S")+'] CSV Error !!')
    dlg.Destroy()
    #pass

def update_log(self,datatext):
    self.logtext.AppendText(datatext + "\n")

def on_exit(self, event):
    self.Close(True)

def OnCloseWindow(self, event):
    db.close()
    cur.close()
    self.Destroy()

def on_warning(self, event):
    msg = """         
     Mini Weather Station
    """
    dlg = wx.MessageDialog(self, msg, "Waring", wx.OK)
    dlg.ShowModal()
    dlg.Destroy()

def on_about(self, event):
    msg = """         
     Mini Weather Station
     RPi2 and Whatsapp
    """
    dlg = wx.MessageDialog(self, msg, "About", wx.OK)
    dlg.ShowModal()
    dlg.Destroy()

if name == 'main':

app = wx.App(False)
WQMP2ET(None, title='Data Sensor')
app.MainLoop()
acbart commented 6 years ago

Assuming you are seeking help on running this in BlockPy, you should know that this code will never work - BlockPy (or rather, Skulpt) does not support WX, XBee, or MySql.