pi_arduino_uart_ex01.py

٤Ƴ٤Ĥ
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
 
 
 
 
 
-
|
|
!
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
-
|
!
 
 
-
!
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
-
!
 
 
 
 
 
 
 
-
!
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
-
|
!
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
-
!
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
-
|
|
|
|
|
|
|
!
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
-
|
!
 
 
 
 
 
-
|
|
|
|
|
|
|
!
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
from tkinter import *
import tkinter as tk
from tkinter import scrolledtext
import serial
import threading
# -*- coding:utf-8 -*-
# 20230503
#
from tkinter.ttk import Scale
from tkinter import colorchooser,filedialog,messagebox
import time
import math
import sys
import requests
import os
import socket
from collections import deque
import subprocess
import copy
import re
import ipget
 
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.gui=pd
        print(self.gui)
        self.gui.set_Remote_Command_Reader(self)
        self.my_address='localhost'
        self.get_my_address()
 
    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 get_my_address(self):
        self.my_address = socket.gethostbyname(socket.gethostname())
        #ipx=ipget.ipget()
        #self.my_address=ipx.ipaddr("wlan0")
        return self.my_address
 
    def parse(self,line):
      #self.python2fwb(">"+line)
      self.gui.parse_command(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("pi_arduino_uart_ex01.py connected to the server")
      except Exception as e:
          msg1="connect error, addr="+addr+" port="+str(self.PORT)
          print(msg1)
          self.gui.write_message(msg1)
          tb=sys.exec_info()[2]
          msg2="[message]{0}".format(e.with_traceback(tb))
          print(msg2)
          self.gui.write_message(msg2)
          return
      addr=self.sock.getsockname()[0]
      print("connect, addr="+addr)
      handle_thread = threading.Thread(target=self.handler, args=(self.sock,), daemon=True)
      handle_thread.start()
 
    def return_message(self,x):
        self.sock.send((x+'\n').encode('utf-8'))
 
    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.gui.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.gui.write_message(msg2)
 
class App:
    arduino_queue=[]
    init_distance=50.0
    allowance_0=4.0
    allowance_1=10.0
    allowance_2=50.0
    def __init__(self,master):
        self.root=root
        self.root.title("command panel")
        self.root.configure(background="white")
        self.root.geometry("850x600")
        self.server_label=Label(self.root, text='server addr')
        self.server_label.place(x=10,y=10)
        self.server_field=Entry(self.root, width=40)
        self.server_field.place(x=100,y=10)
        self.id_label=Label(self.root, text='id')
        self.id_label.place(x=10,y=40)
        self.id_field=Entry(self.root, width=40)
        self.id_field.place(x=100,y=40)
        #self.address_field=Entry(self.root, width=40)
        #self.address_field.place(x=100,y=10)
        self.command_label=Label(self.root, text='command')
        self.command_label.place(x=10,y=60)
        self.command_field=Entry(self.root, width=70)
        self.command_field.place(x=100,y=60)
        self.parse_command_button=Button(self.root, text='parse',bd=2,bg='white',
                                command=self.click_command_button,width=8, relief=RIDGE)
        self.parse_command_button.place(x=700,y=60)
        
        self.arduino_command_label=Label(self.root, text='arduino')
        self.arduino_command_label.place(x=10,y=90)
        self.arduino_command_field=Entry(self.root, width=70)
        self.arduino_command_field.place(x=100,y=90)
        self.arduino_send_button=Button(self.root, text='send',bd=2,bg='white',
                                command=self.arduino_click_button,width=8, relief=RIDGE)
        self.arduino_send_button.place(x=700,y=90)
 
        self.message_frame=tk.Frame(self.root,width=100, height=30)
        self.message_frame.place(x=30,y=120)
        self.message_area=scrolledtext.ScrolledText(self.message_frame)
        self.message_area.pack()
        self.message_line=0
 
        self.id_field.delete(0,END)
        self.id_field.insert(END,'')
        
        self.serial=serial.Serial('/dev/ttyACM0',115200)
        self.serial.flush()
        thread=threading.Thread(target=self.read_loop,args=[],name='thread1')
        ipx=ipget.ipget()
        self.send_arduino("show \""+str(ipx.ipaddr('wlan0'))+"\"")
        self.send_arduino("show \""+str(ipx.ipaddr('eth0'))+"\"")
        thread.start()
 
# Functions are defined here
    def set_Remote_Command_Reader(self,reader):
        self.reader=reader
 
    def set_tcp_server_address(self,address):
        self.server_field.delete(0,END)
        self.server_field.insert(END,address)
 
    def connect(self):
        server=self.server_field.get()
        self.reader.client_start(server)
        
    def shutdown(self):
        os.system("sudo shutdown -h now")
 
    def write_message(self,message):
        self.message_area.insert(tk.END,message)
        self.message_area.insert(tk.END,'\n')
    def send_arduino(self,message):
        self.serial.write(message.encode('utf-8'))
        self.write_message(">"+message)
        self.serial.write('\n'.encode('utf-8'))
        
    def arduino_click_button(self):
        inx=self.arduino_command_field.get()
        print("inx="+inx)
        self.send_arduino(inx)
        self.arduino_command_field.delete(0,END)
 
    def click_command_button(self):
        inx=self.command_field.get()
        print("inx="+inx)
        self.parse_command(inx)
        self.command_field.delete(0,END)
 
    def set_my_id(self,id):
        self.id_field.delete(0,END)
        self.id_field.insert(END,id)
 
    def set_init(self):
        # while True:
        #    l=get distance
        #    if abs(l-init_distance)<allowance
        #         return 
        #    while l>init_distance
        #       back little
        #    while l<init_distance
        #       go little
        for i in range(50):   #while True
             self.send_arduino("get distance.")
             vs=""
             for j in range(10):  # wait for the distance
                  vx=self.arduino_queue.pop(0)
                  if vx==None:
                      time.sleep(0.1)
                  else:
                      vs=vx
             if vs=="":
                  self.reader.return_message("something wrong.")
                  return
             v=float(vs)
             if abs(v-self.init_distance)<self.allowance_0:
                 self.send_arduino("set current 0.0")
                 self.reader.return_message("init succeded.")
                 return
             elif v>self.init_distance+self.allowance_2:
                 dx=(v-self.init_distance)*1.5
                 self.send_arduino("set current "+str(dx)) 
                 self.send_arduino("moveTo 0.0")
             elif v>self.init_distance+self.allowance_1:
                 dx=(v-self.init_distance)*0.7
                 self.send_arduino("set current "+str(dx))
                 self.send_arduino("moveTo 0.0")
             elif v<self.init_distance-self.allowance_2:
                 self.send_arduino("set current 0.0")
                 self.send_arduino("moveTo 10.0")
             elif v<self.init_distance-self.allowance_1:
                 self.send_arduino("set current 0.0")
                 self.send_arduino("moveTo 1.0")
 
    def is_my_id(self,x):
        print("is_my_id("+x+")",end="")
        id=self.id_field.get()
        print(" id="+id)
        return re.match(x,id)
 
    def read_loop(self):
        while True:
            c=self.serial.readline().decode('utf-8').rstrip()
            self.message_line=self.message_line+1
            self.write_message(c)
            #addr=self.server_field.get()
            #rtn=addr+" "+c
            print("return "+c)
            self.reader.return_message(c)
            rx=c.split(' ')
            if len(rx)==2:
               if rx[1]=='mm.':
                    self.arduino_queue.append(rx[0])
    #
    # command
    #    id="<id>" arduino <arduino command>
    #    arduino <arduino command>
    #    set id="<id>"
    #    set init
    #    shutdown
    #
    def parse_command(self,command):
        rest=[""]
        strc=[""]
        ix=[""]
        self.command_field.delete(0,END)
        self.command_field.insert(END,command)
        command=self.r_b(command)
        print("parse_command("+command+")")
        if self.parse_key("id=",command,rest):
            print("parse_key(id="+command+","+rest[0]+")")
            command=self.r_b(rest[0])
            if self.parse_String_Constant(command,strc,rest):
                print("strc="+strc[0]+",rest="+rest[0])
                command=self.r_b(rest[0])
                strcx=strc[0]
                if strcx=="*" :
                    if self.parse_arduino(command):
                        return True
                    else:
                        return False
                elif self.is_my_id(strcx):
                    print("start parse_arduino("+command+",rest)")
                    if self.parse_arduino(command):
                        return True
                    else:
                        return False
                else:
                    return False
            return False
        elif self.parse_key("set ",command,rest):
            command=self.r_b(rest[0])
            if self.parse_key("id=",command,rest):
                command=self.r_b(rest[0])
                if self.parse_String_Constant(command,strc,rest):
                    strcx=strc[0]
                    print("strc="+strcx+",rest="+rest[0])
                    self.set_my_id(strcx)
                    return True
                else:
                    return False
            elif selt.parse_key("init",command,rest):
                self.set_init()
            else:
                return False
        elif self.parse_key("shutdown",command,rest):
            self.shutdown()
            return True
        
    def parse_arduino(self,command):
        rest=[""]
        strc=[""]
        ix=[""]
        command=self.r_b(command)
        if self.parse_key("arduino ",command,rest):
            print("parse_key(arduino "+command+","+rest[0]+")")
            command=self.r_b(rest[0])
            print("xx "+command)
            self.arduino_command_field.delete(0,END)
            self.arduino_command_field.insert(END,command)
            self.send_arduino(command)
            return True
        elif self.parse_key("init",command,rest):
            print("parse_key(init "+command+","+rest[0]+")")
            self.set_init()
            return True
        else:
            return False
 
    def parse_key(self,key,inx,rest):
        keylen=len(key)
        inlen=len(inx)
        if inx.startswith(key):
            rest[0]=inx[keylen:inlen]
            return True
        rest[0]=inx
        return False
 
    def parse_p_int(self,command,ix,rest):
        print("parse_p_int("+command+",ix,rest)")
        i=0
        c=command[0]
        if c in ['0','1','2','3','4','5','6','7','8','9']:
            clen=len(command)
            while True:
                i=i*10+int(c)
                command=command[1:clen]
                clen=len(command)
                if clen==0:
                    ix[0]=i
                    rest[0]=""
                    return True
                print("parse_p_int command="+command)
                c=command[0]
                if not (c in ['0','1','2','3','4','5','6','7','8','9']):
                    ix[0]=i
                    rest[0]=command
                    return True
        rest[0]=command
        ix[0]=0
        return False
 
    def r_b(self,inx):
        rx=[""]
        while self.parse_key(" ",inx,rx):
            inx=rx[0]
        return rx[0]
 
    def parse_String_Constant(self,inx,strc,rest):
        rx=[""]
        xstr=""
        if self.parse_key('"',inx,rx):
            inx=rx[0]
            fx=inx[0]
            xlen=len(inx)
            while fx!='"':
                if xlen==0:
                    return False
                if fx=='\\':
                   inx=inx[1:xlen]
                else:
                   xstr=xstr+fx
                xlen=len(inx)
                inx=inx[1:xlen]
                fx=inx[0]
            if self.parse_key('"',inx,rx):
                strc[0]=xstr
                rest[0]=rx[0]
                return True
        return False
            
if __name__=="__main__":
    root = Tk()
    root.wm_title('Scrolling')
    app = App(root)
    rcr=Remote_Command_Reader(app)
    ip=rcr.get_my_address()
    app.set_tcp_server_address(ip)
    app.connect()
    ip=rcr.get_my_address()
    app.set_tcp_server_address(ip)
    app.set_my_id(ip)
    root.mainloop()

Counter: 91, today: 1, yesterday: 0

トップ   新規 一覧 単語検索 最終更新   ヘルプ   最終更新のRSS