- android - 多次调用 OnPrimaryClipChangedListener
- android - 无法更新 RecyclerView 中的 TextView 字段
- android.database.CursorIndexOutOfBoundsException : Index 0 requested, 光标大小为 0
- android - 使用 AppCompat 时,我们是否需要明确指定其 UI 组件(Spinner、EditText)颜色
我在 Raspberry Pi 3 上从 USB 读取序列号时遇到问题。我正在阅读的设备是 Arduino NANO。那里的代码对于基于 Windows 的机器来说是干净和好的。
但是,在 Raspberry Pi 3 (debian jessie) 上,我发现通过串行读取时 CPU 使用率达到 100%。这些是我安装的包:
python-pygame python-serial python-netifaces cu python-wxgtk3.0
我使用此代码不停地检查串行输入:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import config
from config import officialwebsite
import pygame
from pygame.locals import *
import serial
import sys
import glob
import time
#
####################
# New Fresh class that handle all input types at once
####################
class CInput():
def __init__(self,Logs,Config,myDisplay):
self.Logs=Logs
self.shift=False
self.clock = pygame.time.Clock()
self.Config = Config
self.Lang=None
self.ConfigKeys=Config.ConfigFile['SectionKeys']
self.last_click = 0
self.myDisplay=myDisplay
self.ser = False # Init serial connexion
####### SERIAL
def Serial_Connect(self):
self.SerialBypass = bool(self.Config.GetValue('SectionAdvanced','noserial'))
# Check input serial port (if no param --noserial)
if not self.SerialBypass:
try:
if self.Config.detectedserialport:
serialport=self.Config.detectedserialport
else:
serialport=self.Config.GetValue('SectionGlobals','serialport')
serialspeed = int(self.Config.GetValue('SectionGlobals','serialspeed'))
self.ser = serial.Serial(serialport,serialspeed)
self.Logs.Log("DEBUG","Successfully loaded serial port {} at speed {}".format(serialport,serialspeed))
except:
self.Logs.Log("FATAL","Unable to load serial port : {} . Common errors are : \n * Your board is not connected \n * Your config file is not set properly (pydarts.cfg in your home folder)\n * Your arduino driver is not installed properly (windows only)\n * You're not part of the dialout group (Linux only).\n -- Note : You can use --noserial argument to bypass serial connection.".format(self.Config.GetValue('SectionGlobals','serialport')))
self.myDisplay.PlaySound('whatamess')
self.myDisplay.InfoMessage([self.Lang.lang['serial-issue-1'],self.Lang.lang['serial-issue-2'],self.Lang.lang['serial-issue-3'],officialwebsite,self.Lang.lang['serial-issue-4']],None,None,'middle','small')
sys.exit(2)
else:
self.Logs.Log("DEBUG","Serial connection bypass as requested. No need for a dart board mate !")
#
# Flush
#
def Serial_Flush(self):
if not self.SerialBypass:
try:
self.ser.flushInput() #Flush Serial input values (prevent user to hit while prog sleeps)
except:
self.Logs.Log("DEBUG","Unable to flush input from serial port.")
else:
self.Logs.Log("DEBUG","Bypassing serial port flush")
#
# Read serial connection.
#
def Serial_Read(self,context=False):
DartStroke = False
KeyStroke = False
# Listen on serial cx
try:
# This event (get) solve the bug on windows (waiting screen)
pygame.event.get()
# Read into the serial buffer if there is somthing inside
serdata=False
try:
serdata=self.ser.in_waiting()#pyserial v2.x
except:
pass
try:
serdata=self.ser.inWaiting()#pyserial v3.x
except:
pass
if serdata: #Read only if there is something in the serial buffer (non-blocking mode)
DartStroke=self.ser.read()
DartStroke=DartStroke.decode(encoding='UTF-8')
except Exception as e:
print("Error {}".format(e))
#print(DartStroke)
# Find unique key in config dict. Returns uppercase (only if something has been hit on board)
if DartStroke:
for TheKey, TheConfig in self.ConfigKeys.items():
if TheConfig == DartStroke:
KeyStroke=TheKey.upper()
# Debug Serial Input (only if something has been hit on board)
if DartStroke and KeyStroke:
self.Logs.Log("DEBUG","DEBUGINPUT : You hit \"{}\" which is associated to \"{}\" in your configuration file.".format(DartStroke,KeyStroke))
elif DartStroke and KeyStroke==False:
self.Logs.Log("DEBUG","You hit \"{}\" which doesn't exists in your configuration file.".format(DartStroke))
# If asked to return KEY, else return VAL
if context=='wizard':
return DartStroke
else:
return KeyStroke
#### KEYBOARD & MOUSE (from pygame)
# Context can be different, dependanding from where this method is used. So far : 'menus' or 'game'
#
def KbdAndMouse(self,ktype, specials, context=None):
keypressed = ""
realkey=-1
double_click_duration=500
clicktype=False
events = pygame.event.get()
for event in events:
if event.type == pygame.QUIT:
print("Exit requested")
sys.exit(0)
# Case of Key UP
if event.type == KEYUP:
if pygame.key.name(event.key) == 'left shift':
self.shift=False
# Case of key PRESSED
if event.type == KEYDOWN:
#self.clock.tick(30)
keyname = pygame.key.name(event.key)
unicodekey = event.dict['unicode']
if len(keyname)==1 and unicodekey!='':
keycouple = self.RealKey(unicodekey,context)
else:
keycouple = self.RealKey(keyname,context)
realkey = keycouple[1]# Get pydarts translation of key
realtype = keycouple[0]# Get pydarts translation of key type (alpha, fx, num, etc...)
#print("Key analysis : original {}, translated as {} in unicode and {} in pydarts key".format(keyname,unicodekey,realkey))
if realkey in specials:# return special key if allowed
return realkey
elif realtype in ktype:# Return standard key if allowed/expected
return realkey
# Case of MOUSE BUTTON PRESSED
if event.type == pygame.MOUSEBUTTONDOWN:
#on click
self.clock.tick(30)
self.diff = self.clock.get_time()
if self.diff <= double_click_duration:
clicktype='double-click'
#self.clock.tick()
#self.last_click = 0
else:
clicktype='single-click'
#self.last_click = self.now
if clicktype:
keycouple = self.RealKey(clicktype,context)
realkey = keycouple[1]# Get pydarts translation of key
realtype = keycouple[0]# Get pydarts translation of key type (alpha, fx, num, etc...)
if realkey in specials:
return realkey
# Everything else failed, return -1 (0 is a valid char)
return -1
def ListenInputs(self,ktype=['num','alpha','fx','arrows'], specials = ['enter','tab','backspace','left shift','escape','space','double-click','single-click'] ,WaitFor=[], context='menus'):
SerialInput = False
pyGameInput = -1
while True:
# First try to read serial
if not self.SerialBypass:
#print("Before serial")
SerialInput = self.Serial_Read(context)
#print("After serial")
# If serial returns false, try to read keyboard
if not SerialInput:
#print("Before pyGame Input")
pyGameInput = self.KbdAndMouse(ktype,specials,context)
#print("After pyGame Input")
# If any input return anything, exit from loop
if pyGameInput!=-1:
self.Logs.Log("DEBUG","Input debug : {}".format(pyGameInput))
# Return Serial input if expected (or if nothing expected)
if (SerialInput and WaitFor==[]) or (SerialInput in WaitFor):
return SerialInput
# Return pyGame input if expected (or if nothing expected)
if (pyGameInput!=-1 and WaitFor==[]) or (pyGameInput in WaitFor):
return pyGameInput
#### COMMON
#
# Function to get key and type from current state
#
def RealKey(self,keypressed,context):
if (keypressed == "&" and self.shift) or keypressed=="[1]" or keypressed=="1":
kvalue = 1
ktype = 'num'
elif (keypressed == "world 73" and self.shift) or keypressed=="[2]" or keypressed=="2":
kvalue = 2
ktype = 'num'
elif (keypressed == "\"" and self.shift) or keypressed=="[3]" or keypressed=="3":
kvalue = 3
ktype = 'num'
elif (keypressed == "'" and self.shift) or keypressed=="[4]" or keypressed=="4":
kvalue = 4
ktype = 'num'
elif (keypressed == "(" and self.shift) or keypressed=="[5]" or keypressed=="5":
kvalue = 5
ktype = 'num'
elif (keypressed == "-" and self.shift) or keypressed=="[6]" or keypressed=="6":
kvalue = 6
ktype = 'num'
elif (keypressed == "world 72" and self.shift) or keypressed=="[7]" or keypressed=="7":
kvalue = 7
ktype = 'num'
elif (keypressed == "_" and self.shift) or keypressed=="[8]" or keypressed=="8":
kvalue = 8
ktype = 'num'
elif (keypressed == "world 71" and self.shift) or keypressed=="[9]" or keypressed=="9":
kvalue = 9
ktype = 'num'
elif (keypressed == "world 64" and self.shift) or keypressed=="[0]" or keypressed=="0":
kvalue = 0
ktype = 'num'
elif (keypressed == "=" and self.shift) or keypressed=="[+]":
kvalue = '+'
ktype = 'math'
elif (keypressed == "*" and self.shift==False) or keypressed=="[*]":
kvalue = '*'
ktype = 'math'
elif (keypressed == "-" and self.shift==False) or keypressed=="[-]":
kvalue = '-'
ktype = 'math'
elif (keypressed == ":" and self.shift) or keypressed=="[/]":
kvalue = '/'
ktype = 'math'
elif (keypressed == "world 64" and self.shift) or keypressed=="[0]" or keypressed=="0":
kvalue = 0
ktype = 'math'
elif (keypressed == ";" and self.shift) or keypressed==".":
kvalue = '.'
ktype = 'alpha'
elif keypressed == "down" or keypressed == "up" or keypressed == "right" or keypressed == "left":
kvalue = keypressed
ktype = 'arrows'
elif keypressed == 'escape' and context=='game': # In-game context, escape means ABORT
kvalue='GAMEBUTTON'
ktype='special'
elif keypressed == 'escape': # All others context, it means 'escape'
kvalue=keypressed
ktype = 'special'
elif keypressed == 'space' and context=='game': # In-game context, space means NEXT PLAYER
kvalue='PLAYERBUTTON'
ktype='special'
elif keypressed == 'space': # All other context, space means 'space'
kvalue=keypressed
ktype='special'
elif keypressed == 'enter' or keypressed=='return': # Enter and Return are comfunded volontarily
kvalue='enter'
ktype='special'
elif keypressed == 'tab':
kvalue=keypressed
ktype='special'
elif keypressed == 'backspace':
kvalue=keypressed
ktype='special'
elif keypressed == 'b' and context=='game': # In-game, 'b' means 'BACKUPTURN'
kvalue='BACKUPBUTTON'
ktype='special'
elif (keypressed == 'f' or keypressed=='double-click'): # Everywhere, 'f' and double-click means "Fullscreen"
kvalue='TOGGLEFULLSCREEN'
ktype='special'
elif keypressed == 'left shift':
kvalue=keypressed
ktype='special'
self.shift=True #Enable Shift !
# Other special chars, need to be at the end (based on length)
elif (len(keypressed)== 2 or len(keypressed)==3) and keypressed[:1] == "f": # Detect Fx keys
kvalue = keypressed
ktype = 'fx'
elif len(keypressed)== 1:# Detect any other key (simple alpha keys)
kvalue = keypressed
ktype = 'alpha'
else:
kvalue=None
ktype=None
return [ktype,kvalue]
我不确定如何解决 100% CPU 问题。在某处添加一个 time.sleep(0.3)
语句会有帮助吗?有人对 debian jessie 上的 Raspberry Pi 3 串行 CPU 负载有更多经验吗?
最佳答案
while True:
pygame.time.wait(5)# A few ms to reduce cpu...
True 解决了问题!
关于 python 3 time.sleep() "serial read",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41664667/
目前我有以下内容: $.ajax({ type: 'POST', url: this.action, data: $(this).serialize(), }); 这工作正常,
目前我有以下内容: $.ajax({ type: 'POST', url: this.action, data: $(this).serialize(), }); 这很好用,但
我知道什么是序列化,但对我来说,这是一个无法描述其含义的术语。 为什么我们称序列化为序列化?将对象转换为原始数据(以及膨胀/反序列化,就此而言)有什么意义?谁创造了这个术语,为什么? 最佳答案 它可能
是否可以将数据结构(使用 boost::serialization)序列化为字符串变量或缓冲区(而不是磁盘上的文件)? 最佳答案 当然,让它在stringstream上完成工作。 关于serializ
假设我有以下类型定义,它依赖于常量来指示记录成员的向量长度: type point_t is record x: std_logic_vector(X_WIDTH-1 downto 0);
我尝试序列化一个向量和一个 map 容器,并通过 cout 输出它们的值。然而,我很难理解boost输出的含义。我的代码如下所示: #include #include #include #
我正在尝试将序列化功能添加到我的 Rust 结构之一。这是一个日历事件,看起来像这样: #[derive(PartialEq, Clone, Encodable, Decodable)] pub st
正如主题所暗示的那样,在将大量数据序列化到文件时,我遇到了 boost::serialization 的一个小问题。问题在于应用程序的序列化部分的内存占用大约是被序列化对象内存的 3 到 3.5 倍。
在搜索解决方案时,我得到了 this和 this但我不清楚这个概念,所以无法实现:(。当我尝试更新数据库中的值(特别是日期时间对象)时会发生此错误。以下是我正在使用的代码:- var upd
我收到以下错误, 模板对象不可迭代 def get_AJAX(request, id): data = serializers.serialize("json", Template.objec
由于方便,我正在考虑对我的所有数据 i/o 使用 serialize() 和 deserialize()。但是,我不想在 Julia 更新中被不可读的文件所困扰。 serialize() 和 dese
我有一个通常使用 JMS Serializer 包序列化的实体。我必须在序列化中添加一些不驻留在实体本身中但通过一些数据库查询收集的字段。 我的想法是创建一个自定义对象,用实体字段填充字段并添加自定义
我正在尝试使用 XmlParser 从 xml 文件中删除和添加标签。以下是我在使用“grails run-app”命令部署的 grails 应用程序中执行时运行良好的代码块: def parser
我正在使用 MRUnit 测试 MultipleOutputs。测试用例失败并显示以下消息。 java.lang.ClassCastException: org.apache.hadoop.io.se
本文整理了Java中com.jme3.network.serializing.serializers.ZIPSerializer类的一些代码示例,展示了ZIPSerializer类的具体用法。这些代码
我有一个处理草图,需要与 USB 设备建立 2 个连接。我无法提前判断哪个设备是 USB0 哪个是 USB1。 (不是我至少知道) 其中一台设备发出问候语,另一台设备根本不回答。因此,我编写了带有简单
我在下面有这个代码,我来自 this forum我遵循了。它对我不起作用,但他们声称代码很好。我已经尝试了几种字符串比较方法,例如 string.equals(string)和标准==运营商,仍然没有
当我尝试调用特定的 Web 服务方法时,我收到“Unspecified error”。使用 XMLSpy 我发现参数对象还没有被序列化。 在生成的序列化程序源中,我注意到以下几行: if (!need
在 Rust 中编写 NEAR 智能合约,我的编译器似乎要求通过 API 发送的对象具有 Serialize trait,以及存储在区块链中的对象 BorshSerialize和 BorshDeser
我正在尝试 Kotlin 序列化。按照说明进行设置后,我得到了 Unresolved reference: serializer使用此代码构建错误: val serializer : KSeriali
我是一名优秀的程序员,十分优秀!