Ich poste den einfach mal wie gewohnt.
Daneben sind auch noch einige extra Ausgaben, die ich eingebaut hatte um rauszufinden, was denn mein Problem ist. Ich schiebe es aber nach etlichen Gefummel doch mal auf die Hardware.
Code: Select all
import threading
import Queue
import time
import binascii
import string
import wx
import eg
from eg.WinAPI.SerialPort import SerialPort, EnumSerialPorts
SAMPLE_TIME = 0.00005
WAIT_TIME = 5.0
MyDecoder = eg.IrDecoder(SAMPLE_TIME)
TRANSMITTING = "\x20"
CMDOK = "\x21"
CSERROR = "\x80" #checksum error
TOERROR= "\x81" #Time out error
CMDERROR = "\x82" #Command error undefined command
SETMODERAW = "\x21\xdf" #including checksum
SETMODEUIR = "\x20\xde" #including checksum
GETVERSION = "\x23\xdd" #including checksum
VERSION_OK = "\x01\x04\xFB" #including checksum
DOTXRAW = "\x36"
def calc_checksum(data):
checksum = 0
for i in xrange(len(data)):
checksum += ord(data[i])
checksum %= 256
checksum = (0x100 - checksum) % 256
return chr(checksum)
def get_struct_time(code, start):
tvalue = (ord(code[start+1]) * 256) + ord(code[start+2])
bBits = ord(code[start+3])
bHdr1 = ord(code[start+4])
bHdr0 = ord(code[start+5])
bOff0 = ord(code[start+6])
bOff1 = ord(code[start+7])
bOn0 = ord(code[start+8])
bOn1 = ord(code[start+9])
tvalue += bHdr1 + bHdr0
for i in range(0, bBits):
bit = (ord(code[start + 10 + (i / 8)]) >> (i % 8)) & 1
if (i % 2) == 0:
if bit:
tvalue += bOn1
else:
tvalue += bOn0
else:
if bit:
tvalue += bOff1
else:
tvalue += bOff0
return tvalue
def calc_time(code):
tvalue = 0
if code[0] == DOTXRAW:
# RAW
length = ord(code[1])
tvalue = (ord(code[2]) * 256) + ord(code[3])
for i in range(4, length + 4):
tvalue += ord(code[i])
tvalue = tvalue * (ord(code[-2]) & 0x1F)
#tvalue -= (ord(code[2]) * 256) + ord(code[3])
elif (ord(code[0]) & 0x1F) > 0:
# REMSTRUCT1
repeat = ord(code[0]) & 0x1F
tvalue = get_struct_time(code, 0) * repeat
#tvalue -= (ord(code[1]) * 256) + ord(code[2])
else:
# REMSTRUCT2
tvalue = get_struct_time(code, 0)
repeat = ord(code[26]) & 0x1F
tvalue = tvalue + (get_struct_time(code, 26) * repeat)
return tvalue * SAMPLE_TIME
class MyHexValidator(wx.PyValidator):
def __init__(self):
wx.PyValidator.__init__(self)
self.Bind(wx.EVT_CHAR, self.OnChar)
def Clone(self):
return MyHexValidator()
def TransferToWindow(self):
return True
def TransferFromWindow(self):
return True
def Validate(self, win):
tc = self.GetWindow()
val = tc.GetValue()
for x in val:
if x not in string.hexdigits:
return False
return True
def OnChar(self, event):
key = event.KeyCode()
if key < wx.WXK_SPACE or key == wx.WXK_DELETE or key > 255:
event.Skip()
return
if chr(key) in string.hexdigits:
event.Skip()
return
if not wx.Validator_IsSilent():
wx.Bell()
# Returning without calling event.Skip eats the event before it
# gets to the text control
return
class UirtThread(threading.Thread):
def __init__(self, comport, comspeed, handler):
self.receiveQueue = Queue.Queue(2048)
threading.Thread.__init__(self)
self._want_abort = False
self.comport = comport
self.comspeed = comspeed
self.handler = handler
self.start()
def run(self):
# This is the code executing in the new thread.
eg.plugins.UIRT2.isRunning = True
lasttime = time.clock()
try:
sp = self.sp = SerialPort(self.comport, self.comspeed)
sp.open()
sp.SetRTS(True)
time.sleep(0.05)
sp.SetRTS(False)
time.sleep(0.05)
sp.SetRTS(True)
buffer = ""
success = False
#empty buffer
for i in range(0, 10):
time.sleep(0.05)
response = sp.read(-1)
if len(response) != 0:
print "Data from UIRT, Try:", i, "Length:", len(response), "Chars:", binascii.hexlify(response).upper()
time.sleep(0.05)
else:
break
for i in range(0, 3):
# get version
sp.write(GETVERSION)
time.sleep(0.05)
response = sp.read()
if response != VERSION_OK:
print "Unexpected Data from UIRT while getting Version, Try:", i, "Length:", len(response), "Chars:", binascii.hexlify(response).upper()
eg.PrintError("UIRT2: Wrong version data")
continue
else:
print "Correct Data from UIRT while getting Version, Try:", i, "Length:", len(response), "Chars:", binascii.hexlify(response).upper()
# set raw mode
sp.write(SETMODERAW)
time.sleep(0.05)
response = sp.read()
if response != CMDOK:
print "Unexpected Data from UIRT while setting RAW mode, Try:", i, "Length:", len(response), "Chars:", binascii.hexlify(response).upper()
eg.PrintError("UIRT2: Could not set RAW mode")
continue
else:
print "Correct Data from UIRT while setting RAW mode, Try:", i, "Length:", len(response), "Chars:", binascii.hexlify(response).upper()
success = True
break
if not success:
eg.PrintError("UIRT2: Cannot connect")
eg.plugins.UIRT2.isRunning = False
return
else:
print "UIRT2: Connected to", eg.WinAPI.SerialPort.device(self.comport)
while not self._want_abort:
if not self.receiveQueue.empty():
received_event = self.receiveQueue.get()
if received_event[0] == 1:
n = sp.write(received_event[1])
time.sleep(0.05)
data = sp.read()
#data = sp.read(-1)
if len(data) == 1:
if data == TRANSMITTING:
#Transmitting OK
data = ""
elif data == CMDOK:
#Command OK
data = ""
elif data == CSERROR:
eg.PrintError("UIRT2: Checksum error")
elif data == TOERROR:
eg.PrintError("UIRT2: Time out error")
elif data == CMDERROR:
eg.PrintError("UIRT2: Undefined command error")
else:
eg.PrintError("UIRT2: Error sending IR code. Response:" + binascii.hexlify(data).upper())
else:
self.handler.TriggerEvent(binascii.hexlify(data).upper())
data = ""
while data != CMDOK and not self._want_abort:
sp.write(SETMODERAW)
time.sleep(0.05)
data = sp.read(-1)
#time.sleep(calc_time(received_event[1]) + 0.05)
received_event[2].set()
data = sp.read(-1)
if len(data):
buffer += data
while True:
terminator_pos = buffer.find("\xff")
if terminator_pos < 0:
break
data = []
for c in buffer[2:terminator_pos]:
data.append(ord(c))
buffer = buffer[terminator_pos+1:]
if len(data) < 2:
continue
event = MyDecoder.Decode(data, len(data))
if event:
self.handler.TriggerEvent(event)
else:
time.sleep(0.01)
finally:
sp.write(SETMODEUIR)
sp.close()
eg.plugins.UIRT2.isRunning = False
print "UIRT2: Connection closed"
def abort(self):
self._want_abort = 1
self.join(1.0)
class UIRT2(eg.RawReceiverPlugin):
canMultiLoad = True
def __init__(self):
eg.RawReceiverPlugin.__init__(self)
eg.plugins.UIRT2.isRunning = False
self.AddAction(self.TransmitIR)
self.AddAction(self.SendToUIRT2)
self.AddAction(self.ModifyPICPorts)
def __start__(self, comport=0):
if not eg.plugins.UIRT2.isRunning:
self.thread = UirtThread(comport, 115200, self)
else:
eg.PrintError("UIRT2: Plugin already running")
def __stop__(self):
self.thread.abort()
def SetupConfigDialog(self, dialog, comport=0):
portCtrl = eg.SerialPortChoice(dialog, comport)
dialog.sizer.Add(wx.StaticText(dialog, -1, "COM-Port:"), 0, wx.ALIGN_CENTER_VERTICAL)
dialog.sizer.Add(portCtrl)
return lambda:(
portCtrl.GetValue(),
)
class TransmitIR(eg.ActionClass):
name = "Transmit IR"
def __call__(self, code, wait_till_finished=True):
#print binascii.hexlify(code)
event = threading.Event()
if not self.plugin.isRunning:
eg.PrintError("UIRT2: Plugin stopped")
return
self.plugin.thread.receiveQueue.put((1, code, event))
if wait_till_finished:
event.wait(WAIT_TIME)
if not event.isSet():
eg.PrintError("UIRT2: Transmitting timed out")
def GetLabel(self, *args):
return self.name
def SetupConfigDialog(self, dialog, code=None, wait_till_finished=True):
code1 = ""
code2 = ""
repeatCount = 4
carrier = 0
if code:
code += (48 * "\x00")
if code[0] == DOTXRAW:
length = ord(code[1])
code1 = "R" + binascii.hexlify(code[2:length]).upper()
repeatCount = ord(code[length]) & 0x1F
carrier = ord(code[length]) >> 6
else:
repeatCount = ord(code[0]) & 0x1F
if repeatCount > 0:
carrier = ord(code[0]) >> 6
code1 = binascii.hexlify(code[1:26]).upper()
else:
repeatCount = ord(code[26]) & 0x1F
carrier = ord(code[0]) >> 6
code1 = binascii.hexlify(code[1:26]).upper()
code2 = binascii.hexlify(code[27:48]).upper()
if carrier < 0:
carrier = 0
elif carrier > 3:
carrier = 3
if repeatCount < 1:
repeatCount = 1
elif repeatCount > 31:
repeatCount = 31
sizer = wx.FlexGridSizer(4,2,5,5)
sizer.AddGrowableCol(1)
st1 = wx.StaticText(dialog, -1, "Code 1:")
sizer.Add(st1, 0, wx.ALIGN_CENTER_VERTICAL)
code1Ctrl = wx.TextCtrl(dialog, -1, code1, size=(325,-1))
sizer.Add(code1Ctrl)
st2 = wx.StaticText(dialog, -1, "Code 2:")
sizer.Add(st2, 0, wx.ALIGN_CENTER_VERTICAL)
code2Ctrl = wx.TextCtrl(dialog, -1, code2, size=(275,-1), validator=MyHexValidator())
sizer.Add(code2Ctrl)
st3 = wx.StaticText(dialog, -1, "Repeat:")
sizer.Add(st3, 0, wx.ALIGN_CENTER_VERTICAL)
repeatCtrl = eg.SpinIntCtrl(dialog, -1, repeatCount, 1, 31)
repeatCtrl.SetBestFittingSize((50,-1))
sizer.Add(repeatCtrl, 0)
st3 = wx.StaticText(dialog, -1, "Carrier:")
sizer.Add(st3, 0, wx.ALIGN_CENTER_VERTICAL)
choices = ('35.7 kHz', '37.0 kHz', '38.4 kHz', '40.0 kHz')
carrierCtrl = wx.Choice(dialog, -1, choices=choices)
carrierCtrl.SetSelection(3 - carrier)
sizer.Add(carrierCtrl, 0)
dialog.sizer.Add(sizer, 0, wx.EXPAND)
dialog.sizer.Add((5,5))
cb = wx.CheckBox(dialog, -1, "Pause till transmission finished")
cb.SetValue(wait_till_finished)
dialog.sizer.Add(cb)
def ReturnResult():
code1 = code1Ctrl.GetValue()
if len(code1) == 0:
return None, cb.GetValue()
code2 = code2Ctrl.GetValue()
repeatCount = repeatCtrl.GetValue()
carrier = 3 - carrierCtrl.GetSelection()
if code1[0] == "R":
data = binascii.unhexlify(code1[1:])
bCmd = repeatCount | (carrier << 6)
code = DOTXRAW + chr(len(data) + 2) + data + chr(bCmd)
elif len(code2) == 0:
data = binascii.unhexlify(code1)
bCmd = repeatCount | (carrier << 6)
code = chr(bCmd) + data
else:
bCmd = 0 | (carrier << 6)
bCmd2 = repeatCount | (carrier << 6)
code = chr(bCmd) + binascii.unhexlify(code1) \
+ chr(bCmd2) + binascii.unhexlify(code2)
return code + calc_checksum(code), cb.GetValue()
return ReturnResult
class SendToUIRT2(eg.ActionClass):
name = "Send Command to UIRT2"
def __call__(self, code, wait_till_finished=True, gen_checksum=True):
if not self.plugin.isRunning:
eg.PrintError("UIRT2: Plugin stopped")
return
code = binascii.unhexlify(code)
if gen_checksum:
code += calc_checksum(code)
event = threading.Event()
self.plugin.thread.receiveQueue.put((1, code, event))
if wait_till_finished:
event.wait(WAIT_TIME)
if not event.isSet():
eg.PrintError("UIRT2: Transmitting timed out")
def GetLabel(self, *args):
return self.name
def SetupConfigDialog(self, dialog, code=None, wait_till_finished=True, gen_checksum=True):
if not code:
code = ""
sizer = wx.FlexGridSizer(4,2,5,5)
sizer.AddGrowableCol(1)
st1 = wx.StaticText(dialog, -1, "Code:")
sizer.Add(st1, 0, wx.ALIGN_CENTER_VERTICAL)
codeCtrl = wx.TextCtrl(dialog, -1, code, size=(325,-1), validator=MyHexValidator())
sizer.Add(codeCtrl)
dialog.sizer.Add(sizer, 0, wx.EXPAND)
dialog.sizer.Add((5,5))
gc = wx.CheckBox(dialog, -1, "Generate Checksum")
gc.SetValue(gen_checksum)
dialog.sizer.Add(gc)
dialog.sizer.Add((5,5))
cb = wx.CheckBox(dialog, -1, "Pause till transmission finished")
cb.SetValue(wait_till_finished)
dialog.sizer.Add(cb)
def ReturnResult():
code = codeCtrl.GetValue()
if len(code) == 0:
return None, cb.GetValue(), gc.GetValue()
return code, cb.GetValue(), gc.GetValue()
return ReturnResult
class ModifyPICPorts (eg.ActionClass):
name = "Modify PIC Ports"
picPortChoices = ("Port: A, Pin: 0", "Port: A, Pin: 1", "Port: B, Pin: 0", "Port: B, Pin: 1");
picActionChoices = ("Pulse", "Set", "Clear", "Toggle");
def __call__(self, picPort = 0, picAction = 0, picDuration = 0, wait_till_finished=True):
if not self.plugin.isRunning:
eg.PrintError("UIRT2: Plugin stopped")
return
bDuration = min(255, (picDuration + 3) / 5)
bAction = 0;
if picPort == 0:
bAction = 0
elif picPort == 1:
bAction = 1
elif picPort == 2:
bAction = 8
elif picPort == 3:
bAction = 9
bAction += (picAction << 6)
code = "\x34\x03" + chr(bAction) + chr(bDuration)
#print binascii.hexlify(code).upper()
code += calc_checksum(code)
event = threading.Event()
self.plugin.thread.receiveQueue.put((1, code, event))
if wait_till_finished:
event.wait(WAIT_TIME)
if not event.isSet():
eg.PrintError("UIRT2: Transmitting timed out")
def GetLabel(self, *args):
if args[1] == 0:
return self.picActionChoices[args[1]] + " " + self.picPortChoices[args[0]] + " for " + str(args[2]) + " ms"
else:
return self.picActionChoices[args[1]] + " " + self.picPortChoices[args[0]]
def SetupConfigDialog(self, dialog, picPort = 0, picAction = 0, picDuration = 0, wait_till_finished=True):
sizer = wx.FlexGridSizer(4,4,5,5)
sizer.AddGrowableCol(1)
picActionChoice = wx.Choice(dialog, -1, choices=self.picActionChoices)
picActionChoice.SetSelection(picAction)
sizer.Add(picActionChoice)
picPortChoice = wx.Choice(dialog, -1, choices=self.picPortChoices)
picPortChoice.SetSelection(picPort)
sizer.Add(picPortChoice)
picDurationCtrl = eg.SpinIntCtrl(dialog, -1, picDuration, 0, 1275)
sizer.Add(picDurationCtrl)
text = wx.StaticText(dialog, -1, "ms")
sizer.Add(text, 0, wx.ALIGN_CENTER_VERTICAL)
dialog.sizer.Add(sizer, 0, wx.EXPAND)
dialog.sizer.Add((5,5))
cb = wx.CheckBox(dialog, -1, "Pause till transmission finished")
cb.SetValue(wait_till_finished)
dialog.sizer.Add(cb)
def ReturnResult():
return picPortChoice.GetSelection(), picActionChoice.GetSelection(), picDurationCtrl.GetValue(), cb.GetValue()
return ReturnResult