Skip to content

Instantly share code, notes, and snippets.

@edp1096
Last active August 8, 2018 06:38
Show Gist options
  • Save edp1096/16e978a531acf23157e16b21a1e95e70 to your computer and use it in GitHub Desktop.
Save edp1096/16e978a531acf23157e16b21a1e95e70 to your computer and use it in GitHub Desktop.
# -*- coding: utf-8 -*-
import sys
import threading
import queue
# from kivy.compat import queue
import serial
import time
import kivy
kivy.require('1.9.0')
from kivy.app import App
from kivy.lang import Builder
from kivy.uix.label import Label
from kivy.uix.textinput import TextInput
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.screenmanager import Screen,ScreenManager,NoTransition,FadeTransition
from kivy.clock import Clock
from kivy.config import Config
# 전역 변수
# 템플릿
kvlang = '''
<ScreenManagement>:
ScreenChild:
<ScreenChild>:
name: 'Second'
the_time: _id_lbl_time
BoxLayout:
orientation: 'vertical'
BoxLayout:
Label:
font_name: 'fonts/malgun.ttf'
text: 'Received'
Label:
id: _id_lbl_time
text: "Initial text"
font_name: 'fonts/malgun.ttf'
# color: 0,0,0,1
BoxLayout:
orientation: 'vertical'
BoxLayout:
size_hint_y: None
text: ''
BoxLayout:
Label:
size_hint_x: None
font_name: 'fonts/malgun.ttf'
# color: 0,0,0,1
text: 'Send'
TextInput:
# size_hint_x: None
font_name: 'fonts/malgun.ttf'
color: 1,1,1,1
id: stxt
text: ''
Button:
size_hint_x: None
font_name: 'fonts/malgunbd.ttf'
background_color: (42/255, 24/255, 77/255, 1.0)
text: '전송'
color: 1,1,1,1
on_press:
app.root.app_main.on_send(stxt.text)
'''
# 화면 설정
Config.set('graphics', 'width', '800')
Config.set('graphics', 'height', '270')
# Config.set('graphics', 'fullscreen', 1)
Config.set('graphics','resizable',0)
# 마우스 멀티터치 비활성 - 마우스 우클릭시 주황색 원형 마크가 생성되는 것 방지 목적
Config.set('input', 'mouse', 'mouse,multitouch_on_demand')
# Serial COM
class SerialThread(threading.Thread):
seq = serial.Serial('COM10', 9600, writeTimeout=0.3, timeout=None) # MS-Windows
# seq = serial.Serial('/dev/ttyUSB0', 9600) # Linux
is_run = True
def __init__(self, queue):
threading.Thread.__init__(self)
self.queue = queue
def run(self):
self.text = ""
while self.is_run:
time.sleep(0.05)
if self.seq.inWaiting():
self.text += (self.seq.read(self.seq.inWaiting())).decode('utf-8')
elif (self.seq.inWaiting() != True and self.text != ""):
app_main.scm.get_screen("Second").updateText(self.text)
self.text = ""
class AppMain(App):
def build(self):
self.queue = queue.Queue()
self.thread = SerialThread(self.queue)
self.thread.start()
# self.process_serial() # Tk에서는 되던게 Kivy에서는 안된다.
Builder.load_string(kvlang)
# Builder.load_file("layout.kv") # 한글이 들어가면 안열린다.
self.scm = ScreenManagement()
return self.scm
def on_send(self, data):
'''
Send data via serial port
'''
try:
SerialThread.seq.write(bytes(data, encoding='ascii'))
except serial.serialutil.SerialException:
print("Send failed! Please check equipments connection.")
class ScreenChild(Screen):
def switch(self, index):
self.parent.current = index
def updateText(self, text):
self.the_time.text = text
# pass
class ScreenManagement(ScreenManager):
current_menu = "Menu 2"
app_main = AppMain()
ScreenManager.transition = NoTransition()
# pass
if __name__ == '__main__':
app_main = AppMain()
app_main.run()
SerialThread.is_run = False
@edp1096
Copy link
Author

edp1096 commented Jun 8, 2017

Python 3.5에서 테스트

Python에서 Kivy 설정은 아래 링크들 참고 - 특히, 리눅스(=라즈베리파이)에서는 Cython 선행설치 필수
https://kivy.org/docs/installation/installation-windows.html#installation
https://stackoverflow.com/questions/34943224/how-can-i-bypass-kivy-module-error-importerror-dll-load-failed-the-specified

Pyserial 설치는 pip install pyserial 입력하면 됨

윈도우에서 가상 시리얼포트 구성은 아래 링크의 툴을 사용함
http://com0com.sourceforge.net/

신호 송수신 테스트는 아래 링크의 툴을 사용함
http://blog.daum.net/pg365/276

한글폰트 갖다 놓을 위치 :
 - 윈도우: %파이썬 설치경로%\Lib\site-packages\kivy\data\fonts
 - 리눅스(라즈베리파이): /usr/local/lib/python3.4/dist-packages/kivy/data/fonts
 - 나는 저 위치에 malgun.ttf, malgunbd.ttf 등을 갖다 놓음

시리얼포트 수신 메시지를 표시할 때, 원래는 쓰레드의 queue를 사용해야하나, Tk에서 되던게 Kivy에서는 안되어서 queue를 안 쓰고 억지로 되게 만들어 놓음

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment