예제 #1
0
def SleepCurrent():
    if not openPort():
        jsonReturn = json.dumps(returnData, True)
        print jsonReturn
        return jsonReturn
    sleep(0.1)
    powerOn()
    sleep(0.1)
    for t in range(len(ICOM)):
        ICOM.pop()
    #print ICOM

    #print "sleep current testing``````````"
    #print "exiting bootloader"
    bridge.ExitBootloaderMode()
    bridge.WriteI2CData(0x00, [0x00])
    bridge.WriteI2CData(0x02,
                        [0x09, 0x64, 0x00])  #change sint from low to pull high
    sleep(sleepTime)

    # Current test using pywinusb
    device = hid.HidDeviceFilter(vendor_id=0x04b4,
                                 product_id=0xf123).get_devices()[0]
    #print device
    device.open()
    #sleep(1)
    #readCount=50
    readCount = 100
    for i in range(readCount):
        device.set_raw_data_handler(readData_handler)
        #print device.find_output_reports()[0]
        report = device.find_output_reports()[0]
        readCurrent = [0x00] * 65
        readCurrent[1] = 0x02
        readCurrent[2] = 0x00
        readCurrent[3] = 0xA6
        readCurrent[4] = 0x00
        readCurrent[5] = 0x00
        readCurrent[6] = 0x00
        report.set_raw_data(readCurrent)
        report.send(readCurrent)
        sleep(readInterval)

    #print ICOM
    #ICOMvalue=numpy.mean(ICOM[-readCount:-1])

    ICOMvalue = numpy.median(ICOM[-30:-1])
    #ICOMvalue=float('%0.1f'%ICOMvalue)
    ICOMvalue = int(ICOMvalue) * 10
    returnData['Data'].append(ICOMvalue)
    if ICOMvalue > 20:
        returnData['TestResult'] = 'Fail'
        returnData['ErrorMessage'] = "High Current"
        returnData['ErrorCode'] = 0x43

    device.close()
    powerOff()
    closePort()

    jsonReturn = json.dumps(returnData, True)
    #print jsonReturn
    sleep(1)
예제 #2
0
def raw_test():
    # simple test
    # browse devices...
    #all_hids = hid.find_all_hid_devices()
    #device = all_hids[0]

    device = hid.HidDeviceFilter(vendor_id = 0x0FDE, product_id = 0xCA08).get_devices()[0]

    try:
        device.open()

        for report in device.find_output_reports():
            print report

        # get output handle
        out_report = device.find_output_reports()[0]

        #set custom raw data handler
        device.set_raw_data_handler(sample_handler)

        #print("\nWaiting for data...\nPress any (system keyboard) key to stop...")

        # ack
        #print("send ack\n")
        #cmd = [0x00]*65
        #cmd[0] = 0x41
        #cmd[1] = 0x43
        #cmd[2] = 0x4b
        #cmd[3] = 0x00
        #cmd[4] = 0x00
        #cmd[5] = 0x00
        #out_report.set_raw_data(cmd)
        #out_report.send()

        # heartbeat
        #print("send heartbeat\n")
        cmd = [0x00]*65
        cmd[0] = 0xa6
        cmd[1] = 0x91
        cmd[2] = 0xca
        cmd[3] = 0x45
        cmd[4] = 0x52
        cmd[5] = 0x01
        out_report.set_raw_data(cmd)
        out_report.send()

        # 72/73
        #print("send 72/73\n")
        cmd = [0x00]*65
        cmd[0] = 0x73
        cmd[1] = 0xe5
        cmd[2] = 0x0a
        cmd[3] = 0x26
        cmd[4] = 0x88
        cmd[5] = 0x8b
        out_report.set_raw_data(cmd)
        out_report.send()

        while not kbhit() and device.is_plugged():
            #just keep the device opened to receive events
            sleep(0.5)
        return
    finally:
        device.close()
예제 #3
0
from pywinusb import hid

filter_hid = hid.HidDeviceFilter(vendor_id=0x2234, product_id=0x0006)


def on_data(data):
    print(f"Got message {data}")


all_hid_devices = hid.find_all_hid_devices()
mbed_devices = [d for d in all_hid_devices if "mbed" in d.vendor_name]

if mbed_devices is None:
    raise ValueError("No HID devices found")

# A buffer of bytes representing the values 1-8
# The first byte is the report ID which must be 0
buffer = [0, 1, 2, 3, 4, 5, 6, 7, 8]

mbed_devices[0].open()
# Set custom raw data handler
mbed_devices[0].set_raw_data_handler(on_data)

# Send the message to the Mbed board
out_report = mbed_devices[0].find_output_reports()
out_report[0].set_raw_data(buffer)
out_report[0].send()


class Acceleronmeter:
    def __init__(self):
예제 #4
0
    def btn_event_callback(self):
        button = self.sender()
        if button is None or not isinstance(button, QPushButton):
            return
        button_str = button.text()

        if self.alive:
            if button_str == u"开始单选乒乓":
                s_msg = self.dev_pro.get_echo_cmd_msg(0x11223344, "cur_msg")
                self.usb_snd_hook(s_msg)
                return

            if button_str == u"清空数据":
                self.r_browser.clear()
                self.s_browser.clear()
                return

            if button_str == u"发送题目":
                devid_str = str(self.an_devid_lineedit.text())
                if devid_str:
                    devid = int(str(self.an_devid_lineedit.text()))
                else:
                    devid = 0
                q_type = unicode(self.q_combo.currentText())
                que_t = int(q_type.split(":")[1][2:])
                que_t = (que_t / 10) * 16 + que_t % 10
                # print que_t
                cur_msg = unicode(self.q_lineedit.text())
                msg = self.dev_pro.get_question_cmd_msg(devid, que_t, cur_msg)
                self.usb_snd_hook(msg)
                self.lcd_buf.put(u"S: 发送题目 : %s : %s " % (q_type, cur_msg))
                return

            if button_str == u"发送数据":
                i = 0
                uid_str = str(self.echo_uid_lineedit.text())
                msg = unicode(self.cmd_lineedit.text())
                msg_str = u"S: 发送回显 : %s, UID:" % msg
                if uid_str:
                    uid = int(uid_str)
                    if uid in self.dev_pro.dtqdict:
                        cur_msg = u"uID: %10u %s" % (uid, msg)
                        msg_str = msg_str + " [ %10u ]" % uid
                        s_msg = self.dev_pro.get_echo_cmd_msg(uid, cur_msg)
                        self.usb_snd_hook(s_msg)
                else:
                    for item in self.dev_pro.dtqdict:
                        if item:
                            cur_msg = u"uID: %10u %s" % (item, msg)
                            i = i + 1
                            s_msg = self.dev_pro.get_echo_cmd_msg(
                                item, cur_msg)
                            self.usb_snd_hook(s_msg)
                            msg_str = msg_str + " [ %10u ]" % item
                self.lcd_buf.put(msg_str)
                return

            if button_str == u"查看配置":
                msg = self.dev_pro.get_check_dev_info_msg()
                self.usb_snd_hook(msg)
                self.lcd_buf.put(u"S: 查看设备信息 ")
                return

            if button_str == u"复位端口":
                port_type = unicode(self.port_combo.currentText())
                port = int(port_type.split(":")[1])
                msg = self.dev_pro.get_reset_port_msg(port)
                self.usb_snd_hook(msg)
                self.lcd_buf.put(u"S: 复位端口 ")
                return

            if button_str == u"同步信道":
                ch = int(str(self.ch_lineedit.text()))
                msg = self.dev_pro.get_set_rf_ch_msg(ch)
                self.usb_snd_hook(msg)
                self.lcd_buf.put(u"S: 同步信道 ")
                return

            if button_str == u"停止绑定":
                msg = self.dev_pro.get_bind_stop_msg()
                self.usb_snd_hook(msg)
                self.bind_button.setText(u"开始绑定")
                self.lcd_buf.put(u"S: 停止绑定: 绑定结束!此时刷卡无效")
                return

            if button_str == u"开始绑定":
                msg = self.dev_pro.get_bind_start_msg()
                self.usb_snd_hook(msg)
                self.bind_button.setText(u"停止绑定")
                self.lcd_buf.put(u"S: 开始绑定: 绑定开始!请将需要测试的答题器刷卡绑定!")
                return

            if button_str == u"清除配置":
                msg = self.dev_pro.get_clear_dev_info_msg()
                self.usb_snd_hook(msg)
                self.lcd_buf.put(u"S: 清除配置: ")
                return

            if button_str == u"同步状态":
                devid_str = str(self.devid_lineedit.text())
                if devid_str:
                    devid = int(devid_str)
                else:
                    devid = 0
                uid_str = ""
                led_cn_str = unicode(self.led_combo.currentText())
                led_cn = int(led_cn_str.split(":")[1][2:])
                led_col_str = unicode(self.led_color_combo.currentText())
                led_c = int(led_col_str.split(":")[1][2:])
                beep_cn_str = unicode(self.beep_combo.currentText())
                beep_cn = int(beep_cn_str.split(":")[1][2:])
                motor_cn_str = unicode(self.motor_combo.currentText())
                motor_cn = int(motor_cn_str.split(":")[1][2:])
                # print led_cn,led_c,beep_cn,motor_cn
                if devid:
                    msg = self.dev_pro.get_dtq_ctl_msg(devid, led_cn, led_c,
                                                       beep_cn, motor_cn)
                    uid_str = "[ %10u ]" % devid
                    self.usb_snd_hook(msg)
                else:
                    for item in self.dev_pro.dtqdict:
                        if item:
                            msg = self.dev_pro.get_dtq_ctl_msg(
                                item, led_cn, led_c, beep_cn, motor_cn)
                            uid_str += "[ %10u ]" % item
                            self.usb_snd_hook(msg)
                self.lcd_buf.put(u"S: 同步状态: UID:%s" % uid_str)
                return

            if button_str == u"查看白名单":
                msg = self.dev_pro.get_check_wl_msg()
                self.usb_snd_hook(msg)
                self.lcd_buf.put(u"S: 查看白名单:")
                return

            if button_str == u"添加固件":
                image_path = unicode(
                    QFileDialog.getOpenFileName(self, u'添加固件', './',
                                                u"bin 文件(*.bin)"))
                file_path = unicode(image_path.split("'")[1])
                if len(file_path) > 0:
                    self.fm_lineedit.setText(file_path)
                return

            if button_str == u"升级程序":
                image_path = unicode(self.fm_lineedit.text())
                if len(image_path) > 0:
                    self.dev_pro.dfu_s = 0
                    self.dfu_pro = file_transfer(image_path,
                                                 self.dev_pro.PAC_LEN - 21)
                    self.progressDialog = QProgressDialog(self)
                    self.progressDialog.setWindowModality(Qt.WindowModal)
                    self.progressDialog.setMinimumDuration(5)
                    self.progressDialog.setWindowTitle(u"请等待")
                    self.progressDialog.setLabelText(u"下载中...")
                    self.progressDialog.setCancelButtonText(u"取消")
                    self.progressDialog.setRange(0, 100)
                    self.usb_dfu_timer.start(300)
                return

            if button_str == u"搜索DTQ监测设备":
                self.lcd_buf.put(u"S: 搜索DTQ监测设备 ")
                self.port_frame.port_name_dict = {}
                self.port_frame.uart_scan()
                r_cmd_str = u"R: 搜索监测端口:"
                for item in self.port_frame.port_name_dict:
                    r_cmd_str += "[ %s ]" % self.port_frame.port_name_dict[item]
                self.lcd_buf.put(r_cmd_str)
                return
        else:
            if button_str == u"搜索USB设备":
                self.lcd_buf.put(u"开始查找设备!")
                self.set_target(
                    hid.HidDeviceFilter(vendor_id=JSQ_VID, product_id=JSQ_PID))
예제 #5
0
    logging.basicConfig(filename='Tier1_WatchDog.INFO.log',
                        level=logging.INFO,
                        format='%(asctime)s %(message)s')
else:
    logging.basicConfig(filename='Tier1_WatchDog.log',
                        level=logging.WARNING,
                        format='%(asctime)s %(message)s')
logging.warning(
    '----------------------------------------------------------------------------------------------'
)
logging.warning('Starting new log')
logging.warning('Version 2.0')
# print('-t ' + str(TimeToReact) + ' -l ' + str(LoggingLevel) + ' -c ' + str(CheckTimeOut) + ' -q ' + str(Tier) +
#      ' users: ' + str(users) + ' Snooze ' + str(snooze))
# Hid Lab
hid_devices = hid.HidDeviceFilter(vendor_id=vendor_id).get_devices()
if not hid_devices:
    print('ERROR: no USB relays found, stopping...')
    sys.exit(2)
for device in hid_devices:
    device.open()
    print('DEVICE ' + device.vendor_name + ' is ready')
target_usage = hid.get_full_usage_id(0xff00,
                                     0x00)  # generic vendor page, usage_id = 0
usage_found = False
for report in device.find_feature_reports():
    if target_usage in report:
        # usage found
        report.get()
        usage_found = True
if not usage_found:
예제 #6
0
파일: myJoystick.py 프로젝트: vehar/AHRS
def test_telephony_hook():
    """Browse for non system HID class devices, if a telephony page
    hook usage control is available monitor value change events"""
    # play with this value (or set it if you know your device capabilities)
    # this allows to poll the telephony device for the current usage value
    input_interrupt_transfers = False

    # get all currently connected HID devices we could filter by doing
    # something like hid.HidDeviceFilter(vendor_id = 0x1234), product Id
    # filters (with masks) and other capabilities also available
    all_devices = hid.HidDeviceFilter(vendor_id=0x483).get_devices()

    if not all_devices:
        print("No HID class devices attached.")
    else:
        # search for our target usage (the hook button)
        #target pageId, usageId
        usage_telephony_hook = hid.get_full_usage_id(0x1, 0x1)

        def hook_pressed(new_value, event_type):
            "simple usage control handler"
            # this simple handler is called on 'pressed' events
            # this means the usage value has changed from '1' to '0'
            # no need to check the value
            event_type = event_type  #avoid pylint warnings
            if new_value:
                print("On Hook!")
            else:
                print("Off Hook!")

        for device in all_devices:
            try:
                device.open()

                # browse input reports
                all_input_reports = device.find_input_reports()

                for input_report in all_input_reports:
                    #for v in input_report.keys():
                    #    print input_report[v]
                    if usage_telephony_hook in input_report:
                        #found a telephony device w/ hook button
                        print("\nMonitoring {0.vendor_name} {0.product_name} "\
                                "device.\n".format(device))
                        print("Press any key to exit monitoring " \
                            "(or remove HID device)...")

                        # add event handler (example of other available
                        # events: EVT_PRESSED, EVT_RELEASED, EVT_ALL, ...)
                        device.add_event_handler(
                            usage_telephony_hook, hook_pressed,
                            hid.HID_EVT_CHANGED)  #level usage

                        if input_interrupt_transfers:
                            # poll the current value (GET_REPORT directive),
                            # allow handler to process result
                            input_report.get()

                        while not kbhit() and device.is_plugged():
                            #just keep the device opened to receive events
                            sleep(0.5)
                        return
            finally:
                device.close()
        print("Sorry, no one of the attached HID class devices "\
            "provide any Telephony Hook button")
예제 #7
0
#
# This can be used to:
# - get your connected HID devices
# - listen for a selected HID device
#
# USAGE:
# find_devices() returns a list of HID devices
# autodetect(optional_keyword) tries to autodetect a game controller for you. might not work, and -
# you can use your own keyword to search for it as well.
# assign() to start listening for a device
# sample_handler() gets then triggered from inputs and returns the keypresses
# call close_device() if you wish to stop listening for the device

import pywinusb.hid as hid

hid_filter = hid.HidDeviceFilter()
all_devices = hid_filter.get_devices()
device = None


def find_devices():
    hidlist = []
    if all_devices:  # Found some HID devices
        for i in 0, (len(all_devices) - 1):
            hidlist.append(all_devices[i])
        return hidlist
    # Returns: List of connected HID Devices with one Device in each index starting from [0]
    # Purpose: To get a list of all connected HID Devices


def autodetect(searchable="defaultvariable"):
예제 #8
0
from pywinusb import hid

filter = hid.HidDeviceFilter(vendor_id=0x0525, product_id=0xA4AC)
hid_device = filter.get_devices()
#device = hid_device[0]
#hid_device.open()
#print(hid_device)

filter = hid.HidDeviceFilter(vendor_id=0x0801, product_id=0x3004)
devices = filter.get_devices()
print devices

if devices:
    device = devices[0]
    print "success"

device.open()
out_report = device.find_output_reports()[0]

buffer = [0x00] * 65
buffer[0] = 0x0
buffer[1] = 0x01
buffer[2] = 0x00
buffer[3] = 0x01

out_report.set_raw_data(buffer)
out_report.send()
dev.close()
예제 #9
0
import pywinusb.hid as hid


def readData(data):
    #print(data)
    print("Raw data: {0}".format(data))
    return None

# VID and PID customization changes here...
filter = hid.HidDeviceFilter(vendor_id = 0x03eb, product_id = 0x2402)
hid_device = filter.get_devices()
device = hid_device[0]
device.open()
print(hid_device)

device.set_raw_data_handler(readData)
예제 #10
0
    if user_input == '1':
        delay_time = 0.015625
    elif user_input == '2':
        delay_time = 0.03125
    elif user_input == '3':
        delay_time = 0.25
    elif user_input == '4':
        delay_time = 0.5
    elif user_input == '5':
        delay_time = 1
    else:
        print u"请输入正确的级别编号:"
        ask_user_input()
        
while True:
    device01=hid.HidDeviceFilter (vendor_id=VID01)
    device01=device01.get_devices()
    if len(device01):
        os.system("cls")
        welcome()
        #print test_performance()
        #ask_delay_time()
        ask_user_input()
        printGreen(u"已连接,欢迎使用!")
        device01=device01[0]
        device01.open()
        device01.set_raw_data_handler(sample_handler)
        while device01.is_plugged():
            time.sleep(2)
    else:
        device02=hid.HidDeviceFilter(vendor_id=VID02)
예제 #11
0
class MyFrame(wx.Frame, hid.HidPnPWindowMixin):
    # a device so we could easily discriminate wich devices to look at
    my_hid_target = hid.HidDeviceFilter(vendor_id=target_vendor_id,
                                        product_id=target_product_id)

    def __init__(self, parent):
        wx.Frame.__init__(
            self, parent, -1,
            "Re-plug your USB HID device, watch the command window!...")
        hid.HidPnPWindowMixin.__init__(self, self.GetHandle())
        wx.EVT_CLOSE(self, self.on_close)
        self.device = None  #no hid device... yet

        # kick the pnp engine
        self.on_hid_pnp()

    def on_hid_pnp(self, hid_event=None):
        """This function will be called on per class event changes, so we need
        to test if our device has being connected or is just gone"""
        # keep old reference for UI updates
        old_device = self.device

        if hid_event:
            print("Hey, a hid device just %s!" % hid_event)

        if hid_event == "connected":
            # test if our device is available
            if self.device:
                # see, at this point we could detect multiple devices!
                # but... we only want just one
                pass
            else:
                self.test_for_connection()
        elif hid_event == "disconnected":
            # the hid object is automatically closed on disconnection we just
            # test if still is plugged (important as the object might be
            # closing)
            if self.device and not self.device.is_plugged():
                self.device = None
                print("you removed my hid device!")
        else:
            # poll for devices
            self.test_for_connection()

        if old_device != self.device:
            # update ui
            pass

    def test_for_connection(self):
        all_items = MyFrame.my_hid_target.get_devices()
        if all_items:
            # at this point, what we decided to be a valid hid target is
            # already plugged
            if len(all_items) == 1:
                # this is easy, we only have a single hid device
                self.device = all_items[0]
            else:
                # at this point you might have multiple scenarios
                grouped_items = MyFrame.my_hid_target.get_devices_by_parent()
                print("%d devices now connected" % len(grouped_items))
                if len(grouped_items) > 1:
                    # 1) Really you have multiple devices connected so, make
                    # your rules, how do you help your user to handle multiple
                    # devices?
                    # maybe you here will find out wich is the new device, and
                    # tag this device so is easily identified (i.e. the WiiMote
                    # uses LEDs), or just your GUI shows some arbitrary
                    # identification for the user (device 2 connected)
                    pass
                else:
                    # 2) We have a single physical device, but the descriptors
                    # might might cause the OS to report is as multiple devices
                    # (collections maybe) so, what would be your target device?
                    # if you designed the device firmware, you already know the
                    # answer...  otherwise one approach might be to browse the
                    # hid usages for a particular target...  anyway, this could
                    # be complex, especially handling multiple physical devices
                    # that are reported as multiple hid paths (objects)...
                    # so...  I recommend you creating a proxy class that is
                    # able to handle all your 'per parent id' grouped devices,
                    # (like a single .open() able to handle your buch of
                    # HidDevice() items
                    pass
                # but... we just arbitrarly select the first hid object path
                # (how creative!)
                self.device = all_items[0]
        if self.device:
            self.device.open()
            print("got my device: %s!" % repr(self.device))
        else:
            print("saddly my device is not here... yet :-( ")

    def on_close(self, event):
        event.Skip()
        if self.device:
            self.device.close()
예제 #12
0
import pywinusb.hid as hid
from time import sleep

target_vendor_id = 0x0483

target_usage = hid.get_full_usage_id(0x1, 0x3a) # page, usage

all_devices = hid.HidDeviceFilter(vendor_id = target_vendor_id).get_devices()

if all_devices is None:
    print("vender ID not found")
    exit()

def sample_handler(data):
    print("Decimal: {0}".format(data))
    print("HEX:", [hex(x) for x in data])
    # print("ASCII:", "".join([chr(x) for x in data]))
    print('------')

for device in all_devices:
    device.open()
    for report in device.find_output_reports():
        print(report)
        if target_usage in report:
            device.set_raw_data_handler(sample_handler)
            buffff = [0] * 64
            buffff[0] = 5
            buffff[1] = 0
            buffff[2] = 3
            report.set_raw_data(buffff)
            report.send()
예제 #13
0


""""""
def read_handler(data):
	print data[:10]
	str1 = ''.join(str(hex(e)) for e in data)

#output = sys.stdout
#hid.core.show_hids(output = output)

sys.stdout = codecs.getwriter('mbcs')(sys.stdout)

vendor_num = 0x03eb
product_num =
filter = hid.HidDeviceFilter(vendor_i0x2fffd = vendor_num, product_id = product_num)

# usb 확인
devices = filter.get_devices()
device = devices[0]
device.open()
print device
print "="*10


target_vendor_id = vendor_num
target_usage = hid.get_full_usage_id(0xffff, 0x00)
print "target_usage=",target_usage


# 읽기 핸들러 연결
예제 #14
0
 def get_Hid_USBRelay(self):
     self.filter = hid.HidDeviceFilter(vendor_id=self.USB_CFG_VENDOR_ID,
                                       product_id=self.USB_CFG_DEVICE_ID)
     self.hid_device = self.filter.get_devices()
     self.device = self.hid_device[0]
예제 #15
0
import pywinusb.hid as hid
import time


def sample_handler(data):
    print("Raw data: {0}".format(data))


filter = hid.HidDeviceFilter(vendor_id=0x16c0, product_id=0x0486)
hid_device = filter.get_devices()
print("hid_device:")
print(hid_device)

device = hid_device[0]
print("device:")
print(device)

device.open()

out_report = device.find_output_reports()
print("out_report")
print(out_report)

target_usage = hid.get_full_usage_id(0x00, 0x3f)
device.set_raw_data_handler(sample_handler)
print("target_usage:")
print(target_usage)
#device.close()

data = [0xFF] * 64
예제 #16
0
        if out.startswith(command + "="):
            print(out)
            return out[len(command) + 1:]
        if time() - lastSent >= 0.001:
            sendCommand(command + "?")
            lastSent = time()
    return None


msgX360 = False
msgNone = False

myReport = None

while myReport is None:
    for d in hid.HidDeviceFilter(vendor_id=0x1EAF).get_devices():
        device = d
        device.open()

        for report in device.find_feature_reports():
            if report.report_id == REPORT_ID and report.report_type == "Feature":
                myReport = report
                break

        if myReport is not None:
            reportId = REPORT_ID
            id = query("id")
            if id:
                print(device)
                print(id)
            break
예제 #17
0
import pywinusb.hid as hid

idVender = 0x1d57
idProduct = 0xac08


def readData(data):
    print("Raw Data: {0}".format(data))
    return None


filter = hid.HidDeviceFilter(vendor_id=idVender, product_id=idProduct)
hid_devices = filter.get_devices()
print(hid_devices)
'''
device = hid_devices[0]

device.open()
print(hid_devices)

target_usage = hid.get_full_usage_id(0x00, 0x3f)
device.set_raw_data_handler(readData)
print(target_usage)

report = device.find_output_reports()

print(report)
print(report[0])

buffer = [0xFF]*64
buffer[0] = 63
예제 #18
0
from pywinusb import hid
from time import sleep

SIZE = 128
REPORT_ID = 0


def sample_handler(data):
    print("Raw data: {0}".format(data))


device = hid.HidDeviceFilter(vendor_id=0x1EAF).get_devices()[0]
print(device)
device.open()
device.set_raw_data_handler(sample_handler)

n = 0
while True:
    print("sending")
    out_report = device.find_output_reports()[0]
    buffer = [i for i in range(SIZE + 1)]
    buffer[0] = REPORT_ID  # report id
    buffer[-1] = n
    out_report.set_raw_data(buffer)
    if out_report.send():
        n = (n + 1) & 0xFF
    sleep(2)
예제 #19
0
import time
from msvcrt import kbhit 
import pywinusb.hid as hid

CMD_SERVO_STOP = 0x14
CMD_GET_BATTERY_VOLTAGE = 0x0f
CMD_GET_SERVO_POSITION  = 0x15

def event_handler(new_value, event_type):
    #time.sleep(0.1  )
    print('event', new_value[:23], event_type)

devices = hid.HidDeviceFilter(vendor_id=0x0483, product_id=0x5750).get_devices()

if len(devices) > 0:
    device = devices[0]
    
    device.open()
    print('serial_number:', device.serial_number)

    full_usage_id = hid.get_full_usage_id(0x8c, 0x03)
    device.add_event_handler(full_usage_id, event_handler)


    while not kbhit():
        cmd = CMD_GET_SERVO_POSITION
        data = [6,1,2,3,4,5,6]
        report_data = bytearray(65)
        report_data[0] = 0
        report_data[1] = 0x55
        report_data[2] = 0x55
예제 #20
0
from pywinusb import hid
from time import sleep

REPORT_ID = 20
HID_REPORT_FEATURE = 3

device = hid.HidDeviceFilter(vendor_id = 0x1EAF, product_id = 0x0024).get_devices()[0]
print(device)
device.open()

"""
    uint8_t reportID;
    uint32_t buttons;
    unsigned hat:4;
    unsigned x:10;
    unsigned y:10;
    unsigned rx:10;
    unsigned ry:10;
    unsigned sliderLeft:10;
    unsigned sliderRight:10;
"""

def toBits(n,bits):
    return tuple((n>>i)&1 for i in range(bits))
    
def getByteFromBits(bits,n):
    out = 0
    for i in range(8):
        out += bits[8*n+i] << i
    return out
예제 #21
0
파일: comm.py 프로젝트: vbioret/mbotControl
from pywinusb import hid

# test of serial wifi communication

filter1 = hid.HidDeviceFilter(vendor_id=0x0416, product_id=0xffff)
devices = filter1.get_devices()

if devices:
    device = devices[0]
    print('success')

device.open()
out_report = device.find_output_reports()[0]
print(device.find_output_reports()[0])
my_buffer = [0x0] * 31
my_buffer[0] = 0x0
my_buffer[1] = 0x02
my_buffer[2] = 0x35
my_buffer[3] = 0x0A
print(my_buffer)
out_report.set_raw_data(my_buffer)
print(out_report)
out_report.send(my_buffer)
device.close()
예제 #22
0
import msvcrt
from pywinusb import hid
# controling mBot thru serial wifi with numerical keys 2,4,5,6,8

filter1 = hid.HidDeviceFilter(vendor_id=0x0416,
                              product_id=0xffff)  # find serial dongle
devices = filter1.get_devices()

if devices:
    device = devices[0]
    print("wifi serial line dongle connected")

while True:
    if msvcrt.kbhit():
        key = msvcrt.getch()
        key_number = ord(key)
        print(key_number)  # stroked key number
        if key_number == 113:
            break
        if key_number == 56:  # go ahead
            device.open()
            out_report = device.find_output_reports()[0]
            my_buffer = [0x0] * 31
            my_buffer[0] = 0x0
            my_buffer[1] = 0x02
            my_buffer[2] = 0x31
            my_buffer[3] = 0x0A
            out_report.set_raw_data(my_buffer)
            out_report.send(my_buffer)
            device.close()
        if key_number == 53:  # stop moving
예제 #23
0
    'GREEN': 1,
    'RED': 2,
    "BLUE": 3,
    "AQUA": 4,
    "YELLOW": 5,
    "VIOLET": 6,
    "WHITE": 7
}
DEFAULT_COLORS = ['BLANK']
SPEED = 0.5
Colors = DEFAULT_COLORS
ColorsLock = threading.Lock()
KeepRunning = True
KeepRunningLock = threading.Lock()
# 1294, pID=1320
Device = hid.HidDeviceFilter(vendor_id=0x1294,
                             product_id=0x1320).get_devices()[0]
##Device = hid.HidDeviceFilter( vendor_id = 0x1d34, product_id = 0x0004 ).get_devices()
if Device is None or 'MAIL' not in ` Device `:
    print "Device not found"
    raise Exception("Device not found")

print Device
Device.open()


def setLEDColor(color):
    global Device
    report = Device.find_output_reports()[0]
    print 'color:', color
    print report[0xff000001]
    report[0xff000001][0] = color
예제 #24
0
def mini_check_lut(test_lut, dead_keys):
    global data_receiving_object
    global data_sending_object

    # Main function
    print("")
    print("Mooltipass Keyboard LUT Generation Tool")

    if using_pywinusb:
        # Look for our device
        filter = hid.HidDeviceFilter(vendor_id=0x16d0, product_id=0x09a0)
        hid_device = filter.get_devices()

        if len(hid_device) == 0:
            print("Mooltipass device not found")
            sys.exit(0)

        # Open device
        print("Mooltipass device found")
        device = hid_device[0]
        device.open()
        device.set_raw_data_handler(data_handler)
        report = device.find_output_reports()

        # Set data sending object
        data_sending_object = report[0]
        data_receiving_object = None
    else:
        # Look for our device and open it
        try:
            hid_device = hid.device(vendor_id=0x16d0, product_id=0x09a0)
            hid_device.open(vendor_id=0x16d0, product_id=0x09a0)
        except IOError as ex:
            print(ex)
            sys.exit(0)

        print("Device Found and Opened")
        print("Manufacturer: %s" % hid_device.get_manufacturer_string())
        print("Product: %s" % hid_device.get_product_string())
        print("Serial No: %s" % hid_device.get_serial_number_string())
        print("")

        # Set data sending object
        data_sending_object = hid_device
        data_receiving_object = hid_device

    sendHidPacket(CMD_PING, 4, [0, 1, 2, 3])
    if receiveHidPacket()[CMD_INDEX] == CMD_PING:
        print("Device responded to our ping")
    else:
        print("Bad answer to ping")
        sys.exit(0)

    #keyboardTest(data_sending_object)
    return_val = keyboardCheck(test_lut, dead_keys)

    # Close device
    if not using_pywinusb:
        data_sending_object.close()
    else:
        device.close()

    return return_val
예제 #25
0
 def __init__(self):
     devices = hid.HidDeviceFilter(vendor_id=0x0483).get_devices()
     dev = devices[1]
예제 #26
0
import pywinusb.hid as hid
from time import sleep

vendor_id = 0x1b1c
product_id = 0x0a14

devices = hid.HidDeviceFilter(vendor_id=vendor_id, product_id=product_id).get_devices()

if devices:
    device = devices[1]
    print("Found Device")
    num = int(input("Sidetone Level: "))
    while(num>255 | num<200):
        num = int(input("Sidetone Level: "))
    buffer = [0x0]*64
    buffer[0:16] = [0xFF, 0x0B, 0, 0xFF, 0x04, 0x0E, 0xFF, 0x05, 0x01, 0x04, 0x00, num, 0, 0, 0, 0]
    print(len(buffer))
    try:
        device.open()
        device.send_feature_report(buffer)
    finally:
        device.close()   

else:
    print("no devices")
예제 #27
0
REPORT_ID = 1
REPORT_SIZE = 1


def sendMode(mode):
    data = [REPORT_ID] + [mode]
    myReport.set_raw_data(data)
    myReport.send()


myReport = None
currentMode = None

while myReport is None:
    print("Searching for device...")
    for d in hid.HidDeviceFilter(product_id=0xc629 + 0 * 0xc62b).get_devices():
        if d.vendor_id == 0x1EAF or d.vendor_id == 0x046D:
            device = d
            device.open()

            for report in device.find_feature_reports():
                if report.report_id == REPORT_ID and report.report_type == "Feature":
                    myReport = report
                    break

            if myReport is not None:
                currentMode = myReport.get()
                if len(currentMode) >= 2:
                    currentMode = currentMode[1]
                    break