#author("2023-05-19T19:27:07+09:00","default:TeleportDresser","TeleportDresser")
#author("2023-05-19T19:27:18+09:00","default:TeleportDresser","TeleportDresser")
[[TeleportDresser]]

#code(python){{
# -*- coding:utf-8 -*-
# 20230503
# 20230519
#
from tkinter import *
from tkinter.ttk import Scale
from tkinter import scrolledtext
from tkinter import colorchooser,filedialog,messagebox
import tkinter as tk
import smbus
import time
import math
import PIL.ImageGrab as ImageGrab
import sys
import requests
import os
import socket
import threading
from collections import deque
import subprocess
import copy

class Remote_Command_Reader:
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    HOST = 'localhost'
    PORT = 9998
    def __init__(self,pd):
        print("start Remote_Command_Reader.__init__")
        self.plane_display=pd
        print(self.plane_display)
        self.plane_display.set_Remote_Command_Reader(self)

    def python2fwbln(self,py2x_message):
      msg=py2x_message+'\n'
      self.sock.sendall(msg.encode('utf-8'))
      
    def python2fwb(self,py2x_message):
      msg=py2x_message
      self.sock.sendall(msg.encode('utf-8'))

    def parse(self,line):
      #self.python2fwb(">"+line)
      self.plane_display.parse(line)

    def returnFileList(self):
        cpath=os.getcwd()
        os.chdir("/home/pi/Pictures")
        filenames = [f.name for f in os.scandir()]
        filenames.sort()
        for fn in filenames:
            self.python2fwbln(fn)
        os.chdir(cpath)
    def shutdown(self):
        os.system("sudo shutdown -h now")
      
    def client_start(self,addr):
      """クライアントのスタート"""
      try:
          self.sock.connect((addr, self.PORT))
          print("pic_ex04.py connected to the server")
      except Exception as e:
          msg1="connect error, addr="+addr+" port="+str(self.PORT)
          print(msg1)
          self.plane_display.write_message(msg1)
          tb=sys.exec_info()[2]
          msg2="message]{0}".format(e.with_traceback(tb))
          print(msg2)
          self.plane_display.write_message(msg2)
          return
      handle_thread = threading.Thread(target=self.handler, args=(self.sock,), daemon=True)
      handle_thread.start()
 
    def handler(self,sock):
      """サーバからメッセージを受信し、表示する"""
      print("start handler from pic_ex04.py")
      while True:
          data=b''
          #data=sock.recv(1024)
          try:
              data = sock.recv(1024)
          except Exception as e:
              tb=sys.exec_info()[2]
              msg2="message]{0}".format(e.with_traceback(tb))
              print(msg2)
              self.plane_display.write_message(msg2)
          try:
              #print("[client-recv¡]{}".format(data.decode("utf-8")))
              received=data.decode("utf-8")
              lines=received.splitlines()
              for line in lines:
                  self.parse(line)
          except Exception as e:
              tb=sys.exec_info()[2]
              msg2="message]{0}".format(e.with_traceback(tb))
              print(msg2)
              self.plane_display.write_message(msg2)

class Pic_Element:
    def __init__(self,canvas,editor,count):
        self.canvas=canvas
        self.cx=0
        self.cy=0
        self.r=0
        self.color=editor.get_color()
        self.width=1
        self.status=0 #0:centering, 1:radius deciding, 2:showing, 3:editing,
                      #4:editing, centering, #5:editing, radius deciding.
        self.err=2.0
        self.canvas=canvas
        self.editor=editor
        self.pic_count=count

    def draw(self):
        a=1
    def is_selected(self,mx,my):
        a=1
    def mouse_down(self,x,y):
        a=1
    def mouse_click(self,x,y):
        a=1
    def draw(self):
        a=a
    def show_cross(self,x,y):
        self.cx=x
        self.cy=y
        self.canvas.create_line(self.cx-3,self.cy-3,self.cx+3,self.cy+3,fill="White",width=1)
        self.canvas.create_line(self.cx+3,self.cy-3,self.cx-3,self.cy+3,fill="White",width=1)
    def show_small_box(self,x,y):
        self.cx=x
        self.cy=y
        self.canvas.create_rectangle(self.cx-3,self.cy-3,self.cx+3,self.cy+3,fill="White",width=1)
        

class Circle(Pic_Element):
    def __init__(self,canvas,editor,count):
        super().__init__(canvas,editor,count)
        self.editor=editor
        #self.cx=0
        #self.cy=0
        #self.r=0
        #self.color='green'
        #self.width=1
        #self.status=0 #0:centering, 1:radius deciding, 2:showing, 3:editing,
                      #4:editing, centering, #5:editing, radius deciding.
        #self.err=2.0
        #self.canvas=canvas
        #self.editor=editor
    def set_center(self,px,py):
        self.cx=px
        self.cy=py
    def set_radius(self,rr):
        self.r=rr
    def draw(self):
        #self.editor.write_message("pic "+str(self.pic_count)+",status="+str(self.status)+",color="+str(self.color))
        color=self.color
        width=self.width
        #print("draw color="+color)
        if self.status==0:
            self.show_cross(self.cx,self.cy)
        elif self.status==1:
            x0=self.cx-self.r
            y0=self.cy-self.r
            x1=self.cx+self.r
            y1=self.cy+self.r
            self.canvas.create_oval(x0,y0,x1,y1,width=width,fill=color)
            self.show_cross(self.cx,self.cy)
        elif self.status==2:
            x0=self.cx-self.r
            y0=self.cy-self.r
            x1=self.cx+self.r
            y1=self.cy+self.r
            self.canvas.create_oval(x0,y0,x1,y1,width=width,fill=color)
        elif self.status==3:
            x0=self.cx-self.r
            y0=self.cy-self.r
            x1=self.cx+self.r
            y1=self.cy+self.r
            self.canvas.create_oval(x0,y0,x1,y1,width=width,fill=color)
        elif self.status==4:
            print("draw status 4 pic_count="+str(self.pic_count))
            x0=self.cx-self.r
            y0=self.cy-self.r
            x1=self.cx+self.r
            y1=self.cy+self.r
            self.canvas.create_oval(x0,y0,x1,y1,width=width,fill=color)
            self.show_small_box(self.cx,self.cy)
        elif self.status==5:
            x0=self.cx-self.r
            y0=self.cy-self.r
            x1=self.cx+self.r
            y1=self.cy+self.r
            self.canvas.create_oval(x0,y0,x1,y1,width=width,fill=color)
            self.show_small_box(self.cx,self.cy)

    def select(self,mx,my):
        print("select")
        rx=math.sqrt((self.cx-mx)*(self.cx-mx)+(self.cy-my)*(self.cy-my))
        if abs(rx-self.r)<self.err:
            if self.status==2:
                self.status=4
    def mouse_click(self,mx,my):
        print("mouse_click, status="+str(self.status)+",pic_count="+str(self.pic_count))
        if self.status==0:
            self.cx=mx
            self.cy=my
            self.status=1
        elif self.status==1:
            sqx=(self.cx-mx)*(self.cx-mx)+(self.cy-my)*(self.cy-my)
            self.r=math.sqrt(sqx)
            self.status=2
        elif self.status==2:
            a=1
        elif self.status==3:
            sqx=(self.cx-mx)*(self.cx-mx)+(self.cy-my)*(self.cy-my)
            rx=math.sqrt(sqx)
            d=abs(self.r-rx)
            print("selecting d="+str(d)+",err="+str(self.err))
            if abs(self.r -rx)<self.err:
                self.status=4
                #print("pic "+str(self.pic_count)+" is selected, tuned into status 4.")
        elif self.status==4:
            self.cx=mx
            self.cy=my
            self.status=5
        elif self.status==5:
            self.r=math.sqrt((self.cx-mx)*(self.cx-mx)+(self.cy-my)*(self.cy-my))
            self.status=2
        
    def mouse_move(self,mx,my):
        if self.status==0:
            self.cx=mx
            self.cy=my
        elif self.status==1:
            self.r=math.sqrt((self.cx-mx)*(self.cx-mx)+(self.cy-my)*(self.cy-my))
        elif self.status==2:
            a=1
        elif self.status==3:
            a=1
        elif self.status==4:
            self.cx=mx
            self.cy=my
        elif self.status==5:
            self.r=math.sqrt((self.cx-mx)*(self.cx-mx)+(self.cy-my)*(self.cy-my))
        
    def set_width(self,width):
        self.width=width
    def get_status(self):
        return self.status
    def set_color(self,color):
        print("set_color,status="+str(self.status)+",color-x="+str(self.color)+",new color="+str(color)+",pic_count="+str(self.pic_count))
        if (self.status==0) or (self.status==1) or (self.status==4) or (self.status==5):
            self.color=color
            print("new color="+str(self.color))
    def set_selecting(self):
        self.status=3
    def set_status(self,s):
        self.status=s
        
class Pic_Elements:
    def __init__(self,editor,canvas):
        self.element_list=[]
        self.canvas=canvas
        self.editor=editor
        
    def add(self,element):
        self.element_list.append(element)
    def remove(self,element):
        self.element_list.remove(element)
    def draw(self):
        #print("draw-elements")
        self.editor.canvas.delete('all')
        for ele in self.element_list:
            ele.draw()
    def clear_all(self):
        self.element_list.clear()
    def mouse_click(self,mx,my):
        for element in self.element_list:
            element.mouse_click(mx,my)
        self.draw()
    def mouse_move(self,mx,my):
        for element in self.element_list:
            element.mouse_move(mx,my)
        self.draw()
    def set_color(self,col):
        print("set_color")
        for element in self.element_list:
            element.set_color(col)
    def selecting(self):
        print("selecting")
        for element in self.element_list:
            element.set_selecting()
        
class Draw_Editor:
#Defining Class and constructor of the Program
    def __init__(self,root):

#Defining title and Size of the Tkinter Window GUI
        self.root =root
        self.root.title("Draw for Neopixel Matrix ex01")
        self.root.geometry("600x1200")
        self.root.configure(background="white")
#         self.root.resizable(0,0)
 
#variables for pointer and Eraser   
        self.pointer= "black"
        self.erase="white"

#Widgets for Tkinter Window
    
# Configure the alignment , font size and color of the text
        text=Text(root)
        text.tag_configure("tag_name", justify='center', font=('arial',10),background='#292826',foreground='orange')

# Insert a Text
        text.insert("1.0", "Neopixel Matrix Draw.")

# Add the tag for following given text
        text.tag_add("tag_name", "1.0", "end")
        text.pack()
        
# Pick a color for drawing from color pannel
        self.pick_color = LabelFrame(self.root,text='Colors',font =('arial',10),bd=5,relief=RIDGE,bg="white")
        self.pick_color.place(x=0,y=80,width=120,height=210)

        colors = ['blue','red','green', 'orange','violet','white','yellow','purple','pink','gold','brown','black']
        i=j=0
        for color in colors:
            Button(self.pick_color,bg=color,bd=2,relief=RIDGE,width=3,command=lambda col=color:self.select_color(col)).grid(row=i,column=j)
            i+=1
            if i==6:
                i=0
                j=1

# New Button and its properties   
        self.new_btn= Button(self.root,text="New",bd=4,bg='white',command=self.new_element,width=10,relief=RIDGE)
        self.new_btn.place(x=0,y=290)

# New Button and its properties   
        self.edit_btn= Button(self.root,text="Edit",bd=4,bg='white',command=self.select,width=10,relief=RIDGE)
        self.edit_btn.place(x=0,y=320)

# Erase Button and its properties   
        self.eraser_btn= Button(self.root,text="Eraser",bd=4,bg='white',command=self.eraser,width=10,relief=RIDGE)
        self.eraser_btn.place(x=0,y=350)

# Reset Button to clear the entire screen 
        self.clear_screen= Button(self.root,text="Clear Screen",bd=4,bg='white',command= self.clear_canvas,width=10,relief=RIDGE)
        self.clear_screen.place(x=0,y=380)

# Save Button for saving the image in local computer
        self.save_btn= Button(self.root,text="ScreenShot",bd=4,bg='white',command=self.save_drawing,width=10,relief=RIDGE)
        self.save_btn.place(x=0,y=410)

# Background Button for choosing color of the Canvas
        self.bg_btn= Button(self.root,text="Background",bd=4,bg='white',command=self.canvas_color,width=10,relief=RIDGE)
        self.bg_btn.place(x=0,y=440)

# Background Button for choosing color of the Canvas
        self.bg_btn= Button(self.root,text="show neomatrix",bd=4,bg='white',command=self.show_neomatrix,width=10,relief=RIDGE)
        self.bg_btn.place(x=0,y=470)

#depth
        self.depth_frame= LabelFrame(self.root,text='depth',bd=5,bg='white',font=('arial',10,'bold'),relief=RIDGE)
        self.depth_frame.place(x=0,y=500,height=50,width=120)

        self.depth_entry =Entry(self.depth_frame,width=10)
        self.depth_entry.grid(row=0,column=1,padx=15)

#remote command bridge server
        self.server_field=Entry(self.root,width=50)
        self.server_field.place(x=80,y=20)
#connect Button for connecting to the bridge server
        self.save_btn= Button(self.root,text="connect",bd=4,bg='white',command=self.connect,width=8,relief=RIDGE)
        self.save_btn.place(x=500,y=20)
        
#expression input (3D)
        self.exp_input_field=Entry(self.root,width=50)
        self.exp_input_field.place(x=80,y=50)

#add Button for adding a picture element
        self.save_btn= Button(self.root,text="enter",bd=4,bg='white',command=self.add_circle_expression,width=8,relief=RIDGE)
        self.save_btn.place(x=500,y=50)

#Defining a background color for the Canvas 
        self.canvas = Canvas(self.root,bg='black',bd=5,relief=GROOVE,height=500,width=375)
        self.canvas.place(x=120,y=80)

# Message Area
        self.message_frame=tk.Frame(self.root,width=40,height=20)
        self.message_frame.place(x=20,y=600)
        self.message_area=scrolledtext.ScrolledText(self.message_frame)
        self.message_area.pack()

#Bind the background Canvas with mouse click
        self.canvas.bind("<B1-Motion>",self.mouse_move1)
        self.canvas.bind("<Button-1>",self.mouse_click)
        self.canvas.bind("<Motion>",self.mouse_move)

        
#Picture Elements
        self.pic_elements=Pic_Elements(self,self.canvas)
        self.pic_count=0

# Functions are defined here
    def set_Remote_Command_Reader(self,reader):
        self.reader=reader

    def set_tcp_server_address(self,address):
        self.server_field.insert(END,address)

# Paint Function for Drawing the lines on Canvas
    def mouse_move(self,event):
        mx=event.x
        my=event.y
        #print("mouse_move("+str(mx)+","+str(my)+")")
        self.pic_elements.mouse_move(mx,my)

    def mouse_move1(self,event):
        mx=event.x
        my=event.y
        print("mouse_move1("+str(mx)+","+str(my)+")")
        self.pic_elements.mouse_move1(mx,my)

    def mouse_click(self,event):
        mx=event.x
        my=event.y
        print("mouse_click("+str(mx)+","+str(my)+")")
        self.pic_elements.mouse_click(mx,my)

# Function for choosing the color of pointer  
    def select_color(self,col):
        print("select_color,color="+col)
        self.pointer = col
        self.pic_elements.set_color(self.pointer)
        
    def get_color(self):
        return self.pointer

# Function for creating a circle  
    def new_element(self):
        c=Circle(self.canvas,self,self.pic_count)
        self.pic_elements.add(c)
        self.pic_count=self.pic_count+1

# Function for defining the eraser
    def eraser(self):
        self.pointer= self.erase

# Function for choosing the background color of the Canvas    
    def canvas_color(self):
        color=colorchooser.askcolor()
        self.canvas.configure(background=color[1])
        self.erase= color[1]

# Function for clear the Canvas    
    def clear_canvas(self):
        #print("clear_canvas")
        self.canvas.delete('all')
        self.pic_elements.clear_all()

    def clear_plane(self):
        try:
            #print("clear_plane")
            i2c = smbus.SMBus(1) # 注:ラズパイのI2Cポート
            addrs = [0x30,0x31,0x32,0x33]
            i2c.write_byte(addrs[0],0x00)
            i2c.write_byte(addrs[1],0x00)
            i2c.write_byte(addrs[2],0x00)
            i2c.write_byte(addrs[3],0x00)
        except Exception as e:
            msg1="clear_plane, i2c error." 
            print(msg1)
            self.write_message(msg1)
            tb=sys.exec_info()[2]
            msg2="message]{0}".format(e.with_traceback(tb))
            print(msg2)
            self.write_message(msg2)

    def show_plane(self):
        try:
            #print("show_plane")
            i2c = smbus.SMBus(1) # 注:ラズパイのI2Cポート
            addrs = [0x30,0x31,0x32,0x33]
            i2c.write_byte(addrs[0],0x01)
            i2c.write_byte(addrs[1],0x01)
            i2c.write_byte(addrs[2],0x01)
            i2c.write_byte(addrs[3],0x01)
        except Exception as e:
            msg1="show_plane, i2c error." 
            print(msg1)
            self.write_message(msg1)
            tb=sys.exec_info()[2]
            msg2="message]{0}".format(e.with_traceback(tb))
            print(msg2)
            self.write_message(msg2)

# Function for clear the Canvas    
    def select(self):
        print("select")
        self.pic_elements.selecting()

# Function for adding ciecle of the expression
    def add_circle_expression(self):
        exp=self.exp_input_field.get()
        self.parse(exp)

    def write_message(self,message):
        self.message_area.insert(END,message)
        self.message_area.insert(END,'\n')
        
    def parse(self,exp):
        #print(exp)
        #self.write_message(exp)
        depthx=self.depth_entry.get()
        #print(depthx)
        if depthx==None or depthx=="":
            depth=0
        else:
            depth=int(depthx)
        #print("depth="+str(depth))
        exp2=exp.split()
        for w in exp2:
            print(w+" ")
        cx=0
        cy=0
        cz=0
        r=0
        color="blue"
        if exp2[0]=="add":
            if exp2[1]=="ball":
                cx=int(exp2[2])
                cy=int(exp2[3])
                cz=int(exp2[4])
                r=int(exp2[5])
                color=exp2[6]
                #self.write_message("ball-("+str(cx)+","+str(cy)+","+str(cz)+") r="+str(r)+",color="+color)
                cz2=depth-cz
                r1sq=r*r-cz2*cz2
                if r1sq>0:
                    r2=math.sqrt(r1sq)
                    cc=Circle(self.canvas,self,self.pic_count)
                    cc.set_center(cx,cy)
                    cc.set_radius(r2)
                    cc.set_color(color)
                    cc.set_status(2)
                    self.pic_elements.add(cc)
                    self.pic_elements.draw()
        if exp2[0]=="set":
            if exp2[1]=="depth":
                depth=exp2[2]  #depth
                self.depth_entry.delete(0,END)
                self.depth_entry.insert(END,depth)
        if exp2[0]=="clear":
            if exp2[1]=="canvas":
                self.clear_canvas()
            elif exp2[1]=="plane":
                self.clear_plane()
        if exp2[0]=="show":
            if exp2[1]=="canvas":
                self.show_neomatrix()
            elif exp2[1]=="plane":
                self.show_plane()
        if exp2[0]=="shutdown":
            self.shutdown()
        if exp2[0]=="setpic4":
            self.setpic4(exp2)

# connect
    def connect(self):
        server=self.server_field.get()
        self.reader.client_start(server)
        
    def shutdown(self):
        os.system("sudo shutdown -h now")

    def setpic4(self,exp2):
        # setpic4 ix iy r0 g0 b0 r1 g1 b1 r2 g2 b2 r3 g3 b3
        ih=int(exp2[1])
        iw=int(exp2[2])
        #self.write_message("setpic4 "+str(exp2[1])+" "+str(exp2[2]))
        r0=int(exp2[3])
        g0=int(exp2[4])
        b0=int(exp2[5])
        r1=int(exp2[6])
        g1=int(exp2[7])
        b1=int(exp2[8])
        r2=int(exp2[9])
        g2=int(exp2[10])
        b2=int(exp2[11])
        r3=int(exp2[12])
        g3=int(exp2[13])
        b3=int(exp2[14])
        
        i2c = smbus.SMBus(1) # 注:ラズパイのI2Cポート
        #
        # command:
        #   clear... 0x00
        #   show ... 0x01
        #   set1 ix,iy,r,g,b
        #         ... 0x02  *,*,  *,*,*
        #   setn ix,iy,n, r0,g0,b0, ..r(n-1),g(n-1),b(n-1)   n<=8
        #         ... 0x03 *,*, *, *,*,*, ..., *,*,*
        #
        #pixels=[[(0,0,0) for j in range(jmax)] for i in range(imax)]
          
        addrs = [0x30,0x31,0x32,0x33]
        fourpix=[0x00, 0x00, 0x04, 0,0,0, 0,0,0, 0,0,0, 0,0,0]
        k=0
        fourpix[3+k*3+0]=r0
        fourpix[3+k*3+1]=g0
        fourpix[3+k*3+2]=b0
        k=1
        fourpix[3+k*3+0]=r1
        fourpix[3+k*3+1]=g1
        fourpix[3+k*3+2]=b1
        k=2
        fourpix[3+k*3+0]=r2
        fourpix[3+k*3+1]=g2
        fourpix[3+k*3+2]=b2
        k=3
        fourpix[3+k*3+0]=r3
        fourpix[3+k*3+1]=g3
        fourpix[3+k*3+2]=b3
        fourpix[0]=ih
        fourpix[1]=int(iw%4)
        i2c_addr=addrs[int(iw/4)]
        try:
            i2c.write_i2c_block_data(i2c_addr,0x03,fourpix)
        except Exception as e:
            msg1='write_i2c_block_data error at setpic4 :('+str(ih)+','+str(iw)+')'
            print(msg1)
            self.write_message(msg1)
            tb=sys.exec_info()[2]
            msg2="message]{0}".format(e.with_traceback(tb))
            print(msg2)
            self.write_message(msg2)
        time.sleep(0.0005)

# Function for saving the image file in Local Computer
    def save_drawing(self):
        try:
            # self.background update()
            file_ss =filedialog.asksaveasfilename(defaultextension='jpg')
            #print(file_ss)
            x=self.root.winfo_rootx() + self.canvas.winfo_x()
            #print(x, self.background.winfo_x())
            y=self.root.winfo_rooty() + self.canvas.winfo_y()
            #print(y)

            x1= x + self.canvas.winfo_width() 
            #print(x1)
            y1= y + self.canvas.winfo_height()
            #print(y1)
            ImageGrab.grab().crop((x , y, x1, y1)).save(file_ss)
            messagebox.showinfo('Screenshot Successfully Saved as' + str(file_ss))

        except:
            print("Error in saving the screenshot")
            
    def return_image(self):
        x=self.root.winfo_rootx() + self.canvas.winfo_x()+10
        #print(x, self.background.winfo_x())
        y=self.root.winfo_rooty() + self.canvas.winfo_y()+10
        #print(y)

        x1= x + self.canvas.winfo_width() -12
        #print(x1)
        y1= y + self.canvas.winfo_height()-12
        #print(y1)
        img=ImageGrab.grab().crop((x , y, x1, y1))
        return img

    def show_neomatrix(self):
        img=self.return_image()
        off_x=0
        off_y=0
        
        imax=75
        jmax=16

        img_width, img_height=img.size
        print('width:',img_width)
        print('height:',img_height)
        dx=img_width/jmax
        dy=img_height/imax
        i2c = smbus.SMBus(1) # 注:ラズパイのI2Cポート
        #
        # command:
        #   clear... 0x00
        #   show ... 0x01
        #   set1 ix,iy,r,g,b
        #         ... 0x02  *,*,  *,*,*
        #   setn ix,iy,n, r0,g0,b0, ..r(n-1),g(n-1),b(n-1)   n<=8
        #         ... 0x03 *,*, *, *,*,*, ..., *,*,*
        #
        pixels=[[(0,0,0) for j in range(jmax)] for i in range(imax)]
          
        addrs = [0x30,0x31,0x32,0x33]
        fourpix=[0x00, 0x00, 0x04, 0,0,0, 0,0,0, 0,0,0, 0,0,0]
        for i in range(imax):
            for j in range(jmax):
                x=off_x+j*dx
                y=off_y+i*dy
                rgb=img.getpixel((x,y))
                pixels[i][j]=rgb

        i2c.write_byte(addrs[0],0x00)
        i2c.write_byte(addrs[1],0x00)
        i2c.write_byte(addrs[2],0x00)
        i2c.write_byte(addrs[3],0x00)
        for i in range(imax):
          for j in range(4):
            for k in range(4):
              p=pixels[i][4*j+k]
              fourpix[3+k*3+0]=p[0]
              fourpix[3+k*3+1]=p[1]
              fourpix[3+k*3+2]=p[2]
            fourpix[0]=i;
            fourpix[1]=0;
            i2c_addr=addrs[j]
            try:
              i2c.write_i2c_block_data(i2c_addr,0x03,fourpix)
            except Exception as e:
                msg1='i2c write error at :('+str(i)+','+str(j)+')'
                print(msg1)
                self.write_message(msg1)
                tb=sys.exec_info()[2]
                msg2="message]{0}".format(e.with_traceback(tb))
                print(msg2)
                self.write_message(msg2)
            time.sleep(0.0005)
        i2c.write_byte(addrs[0],0x01)
        i2c.write_byte(addrs[1],0x01)
        i2c.write_byte(addrs[2],0x01)
        i2c.write_byte(addrs[3],0x01)

    def r_b(self,str):
        rtn=copy.copy(str)
        while rtn[0]==' ':
            ls=len(rtn)
            rtn=rtn[-1:]
        return rtn

    def is_key(self,skey,sin,rest):
        key_len=len(skey)
        sin_len=len(sin)
        if sin.startswith(sky):
            sout[0]=sin[-(sin_len-key_len):]
            return True
        return False
    def is_hex_char(self,c):
        if ('0'<=c and c<='9'):
            return c-'0'
        if ('a'<=c and c<='f'):
            return c-'a'+10
        return -1
    def is_hex(self,line,hex,rest):
        p=0
        c=line[p]
        hex[0]=0
        if c<0:
            return False
        while c>=0:
            p=p+1
            hex[0]=hex[0]*16+c
            c=line[p]
        rest[0]=line[-p:]
        return True
    def is_str_const(self,line,str_const,rest):
        p=0
        line_len=len(line)
        str_const[0]=""
        if line[0]=='\"' or line[0]=='\'':
            p=p+1
            while p<line_len:
                c=line[p]
                if c=='\"' or c=='\'':
                    p=p+1
                    sout[0]=line[-p:]
                    return True
                if c=='\\':
                    p=p+1
                    str_const[0]=str_const[0]+line[p]
                    p=p+1
                else:
                    str_const[0]=c
                    p=p+1
        return False
            
    def recv_neopix_commands(self,command):
        i2c = smbus.SMBus(1) # 注:ラズパイのI2Cポート
        #
        # command:
        #   clear... 0x00
        #   show ... 0x01
        #   set1 ix,iy,r,g,b
        #         ... 0x02  *,*,  *,*,*
        #   setn ix,iy,n, r0,g0,b0, ..r(n-1),g(n-1),b(n-1)   n<=8
        #         ... 0x03 *,*, *, *,*,*, ..., *,*,*
        #   set4 ix iy  r0,g0,b0, ..r3,g3,b3  
        #         ... 0x03 *,*, *, *,*,*, ..., *,*,*
        #
        rest=[command]
        if not self.is_key("neopix",command,rest):
            return False
        command=self.r_b(rest[0])
        pixels=[[(0,0,0) for j in range(jmax)] for i in range(imax)]
          
        addrs = [0x30,0x31,0x32,0x33]
        fourpix=[0x00, 0x00, 0x04, 0,0,0, 0,0,0, 0,0,0, 0,0,0]
        
        if self.is_key("clear.",command,rest):
            i2c.write_byte(addrs[0],0x00)
            i2c.write_byte(addrs[1],0x00)
            i2c.write_byte(addrs[2],0x00)
            i2c.write_byte(addrs[3],0x00)
            return
        if self.is_key("show.",command,rest):
            i2c.write_byte(addrs[0],0x01)
            i2c.write_byte(addrs[1],0x01)
            i2c.write_byte(addrs[2],0x01)
            i2c.write_byte(addrs[3],0x01)
            return
        if self.is_key("set4 ",command,rest): #  set4 ix iy r0,g0,b0,...
            #                                               
            command=r_b(rest[0])
            hex=[0]
            if not self.is_hex(command,hex,rest):  # ix ...0 to 74
                return False
            ix=hex[0]
            command=r_b(rest[0])
            if not self.is_hex(command,hex,rest):  # iy ...0 to 3
                return False
            iy=hex[0]
            for k in range(4):
                command=r_b(rest[0])
                if not self.is_hex(command,hex,rest): #r
                    return False
                fourpix[3+k*3+0]=hex[0]
                command=r_b(rest[0])
                if not self.is_key(command,",",rest):
                    return False
                command=r_b(rest[0])
                if not self.is_hex(command,hex,rest): #g
                    return False
                fourpix[3+k*3+1]=hex[0]
                command=r_b(rest[0])
                if not self.is_key(command,",",rest):
                    return False
                command=r_b(rest[0])
                if not self.is_hex(command,hex,rest): #b
                    return False
                fourpix[3+k*3+2]=hex[0]
            fourpix[0]=ix;
            fourpix[1]=0;
            i2c_addr=addrs[iy]
            try:
              i2c.write_i2c_block_data(i2c_addr,0x03,fourpix)
            except Exception as e:
                msg1='write_i2c error at setpic4 :('+str(ih)+','+str(iw)+')'
                print(msg1)
                self.write_message(msg1)
                tb=sys.exec_info()[2]
                msg2="message]{0}".format(e.with_traceback(tb))
                print(msg2)
                self.write_message(msg2)
            time.sleep(0.0005)

if __name__=="__main__":
    root = Tk()
    p=Draw_Editor(root)
    rcr=Remote_Command_Reader(p)
    p.set_tcp_server_address("localhost")
    p.connect()
    root.mainloop()
}}
----
#counter

トップ   編集 差分 バックアップ 添付 複製 名前変更 リロード   新規 一覧 単語検索 最終更新   ヘルプ   最終更新のRSS