I bought this [IR Sensor and Remote][1] to use with my Raspberry Pi 3.
I have LIRC setup and I am able to detect an input from the IR Remote using the commands below:
sudo /etc/init.d/lirc stop
mode2 -d /dev/lirc0
When I run the above commands, I am able to detect input from the IR Remote. When I press any button on the IR REmote, I get an output like:
My question is - in the output above, I pressed '2" on the remote. How shall I go about deciphering (in python) which button is really pressed?
Update 1:
I tried using the python-lirc package but I get error on this line:
The previous answers shortcuts the lirc decoding. Since you have a working mode2 the kernel driver works and sends correct data to lircd. However, mode2 does not tell you if the decoding works.
To check the decoding you use irw(1). Until you have working output from this program, you don't know if lirc can decode your remote.
The lircrc file described above is used to transform the generic button presses (as shown by irw) to application-specific commands. To debug this file you use ircat(1).
When you have working output from irw(1) and ircat(1) your lirc setup is complete. A working lirc setup is really required before using any python package. BTW, as of upcoming 0.10.0 lirc will have native python bindings.
A comprehensive guide to setup lirc can be found at http://lirc.org/html/configuration-guide.html
You probably do not want to use the mode2 output for this. There is a Python library available (Here) which would likely be a much better way to go for this project.
Code:
import lirc
sockid = lirc.init("myprogram")
print(lirc.nextcode())
lirc.deinit()
lircrc configuration file
begin
button = 1 # what button is pressed on the remote
prog = myprogram # program to handle this command
config = one, horse # configs are given to program as list
end
begin
button = 2
prog = myprogram
config = two
end
Results after pressing button 1
['one', 'horse']
These days there is no need to use lirc as IR events are handled through the kernel.
In my case I setup an IR receiver on a GPIO pin in /boot/config.txt
dtoverlay=gpio-ir,gpio_pin=16
Then installed evdev
pip install evdev
Reboot, and the following worked (your input device path my vary)
from evdev import InputDevice, categorize, ecodes
dev = InputDevice('/dev/input/event0')
for event in dev.read_loop():
print(event)
When pressing some buttons on the remote I get:
$> sudo python3 irtest.py
device /dev/input/event0, name "gpio_ir_recv", phys "gpio_ir_recv/input0"
event at 1639133806.295636, code 04, type 04, val 64
event at 1639133806.295636, code 00, type 00, val 00
event at 1639133806.405607, code 04, type 04, val 64
event at 1639133806.405607, code 00, type 00, val 00
event at 1639133808.745610, code 04, type 04, val 16
...
Related
I am currently experiencing difficulties using PyInstaller on a code relying on Pymeasure library. The program is working fine from the prompt, but not when started from the executable generated by PyInstaller.
Here is an simple example of a code working from prompt but not when frozen:
import visa
from pymeasure.instruments.keithley import Keithley2000, Keithley2400
rm = visa.ResourceManager()
list_available = rm.list_resources()
print(list_available)
keithley = Keithley2400("GPIB1::23")
keithley.apply_current() # Sets up to source current
keithley.source_current_range = 10e-3 # Sets the source current range to 10 mA
keithley.compliance_voltage = 10 # Sets the compliance voltage to 10 V
keithley.source_current = 0 # Sets the source current to 0 mA
keithley.enable_source() # Enables the source output
keithley.measure_voltage() # Sets up to measure voltage
keithley.ramp_to_current(5e-3) # Ramps the current to 5 mA
print(keithley.voltage) # Prints the voltage in Volts
keithley.shutdown() # Ramps the current to 0 mA and disables output
Here is the output when I run the executable:
Please note that I have PyVISA 1.9.1 installed.
Why do I get this error and how do I fix that ?
You need to make sure you include the package metadata for PyVisa in your PyInstaller project. PyInstaller has a utility hook for that job; create a hook-pyvista.py hook file (if you don’t already have one) with:
from PyInstaller.utils.hooks import copy_metadata
datas = copy_metadata("pyvisa")
and tell PyInstaller about it with the --additional-hooks-dir command-line switch. See the documentation on how hooks work for more details.
pymeasurement relies on the pyvisa.__version__ attribute to determine if you have installed the correct version of that project. But pyvisa.__version__ defaults to "unknown" unless it can locate its metadata files, which would provide pkg_resources with the required metadata to retrieve the version for it.
You can verify that PyVisa was installed correctly by importing it yourself and testing the __version__ attribute:
import pyvisa
print("PyVisa version", pyvisa.__version__)
Are you sure you are connected to the instrument, your code references "GPIB1::23" but your print(list_available) returns "GPIB1::24"?
I have some problems with the MotorBridgeCape. I have all my software and I found most of it at GitHub.com at github.com/Seeed-Studio/MotorBridgeCapeforBBG_BBB and at their Wiki at seeedstudio.com/wiki/Motor_Bridge_Cape_v1.0.
Here is my issue. I connect my battery, two motors, and I run the .py file for DC Motors from their Wiki page. I get an error. The error reads as follows:
•Error accessing 0x4B: Check your I2C address
I checked online at their site. The seeedstudio.com site, in the forum section, stated that in 2014 there was an addressed answer. This answer was to update the firmware. I go into my BBB/BBG with the MotorBridgeCape attached and I download the .zip file and then unzip it.
The update to the firmware is as follows:
1.Connect cape to your BBG/BBB, download http://www.seeedstudio.com/wiki/images/ ... e_v1.0.zip to your BBG/BBB
2.unzip the file
3.Go to the directory Motor Bridge Cape V1.0 (cd Motor Bridge Cape V1.0)
4.upload firmware (make flash_firmware)
Once I unzip the .zip file, I get a "directory." The directory is listed as Motor Bridge Cape v1.0. I have no underscores in the file/directory.
So, it is not listed as Motor_Bridge_Cape_v1.0 and I cannot move to that file/directory. So, I used "\" to move to that directory.
So, I get to the directory stated and I use "make flash_Firmware". That gets me errors, too.
Here is the code for the MotorBridgeCapeforBBG_BBB:
https://github.com/Seeed-Studio/MotorBridgeCapeforBBG_BBB/blob/master/BBG_MotorBridgeCape/MotorBridge.py
Please see:
from Adafruit_I2C import Adafruit_I2C
import Adafruit_BBIO.GPIO as GPIO
import time
Reset = "P9_23"
MotorBridge = Adafruit_I2C(0x4b)
GPIO.setup(Reset, GPIO.OUT)
ReadMode = 0
WriteMode = 1
DeAddr = 0X4B
ConfigValid = 0x3a6fb67c
DelayTime = 0.005
This software above uses the Adafruit_I2C. Is there a way to change Adafruit_I2C to another "import" of GPIOs that does not have a bug?
The I2C import from Adafruit has a bug in it. If I can change the I2C import to import other GPIOs, like GPIO_46 and so on, I should be able to use the MotorBridgeCapeforBBG_BBB in my current code to make things go.
Please see:
import MotorBridge
import time
MotorName = 1
ClockWise = 1
CounterClockWise = 2
PwmDuty = 90
Frequency = 1000
if __name__=="__main__":
motor = MotorBridge.MotorBridgeCape()
motor.DCMotorInit(MotorName,Frequency)
while True:
motor.DCMotorMove(MotorName,ClockWise,PwmDuty)
time.sleep(2)
motor.DCMotorMove(MotorName,CounterClockWise,PwmDuty)
time.sleep(2)
print "hello"
motor.DCMotorStop(MotorName)
time.sleep(2)
Seth
P.S. Any recommendations would be very helpful.
I changed the line
MotorBridge = Adafruit_I2C(0x4b)
to
MotorBridge = Adafruit_I2C(0x4b,2)
and it worked for me. Also make sure you have python-smbus installed. See this webpage for more information.
Okay...
I checked out the BBG and the Motor Bridge Cape long enough. I did as you stated in the above answer. Thank you. It was that additional 2 in the sequence of the software. I also needed python smbus to run the software correctly.
Seth
An update to this item is now available on github.com at https://github.com/silver2row/bbg/blob/master/MBC/MotorBridge.py.
Also, you can view the README at the beginning of the github repository for accessing smbus2, getting your smbus2 line 302 changed, and for some simple source to test your findings.
There are a lot of changes to set up on your MotorBridge.py file. Please view the differences and change them accordingly.
Seth
the Motor Bridge Cape "needs" the Adafruit_GPIO.I2C library since the Adafruit_BBIO.I2C library is not existent right now. Also...this is old news since the Adafruit_GPIO.I2C library has been deprecated.
It is read only now. You can find that info. here: https://github.com/adafruit/Adafruit_Python_GPIO/blob/master/Adafruit_GPIO/I2C.py.
This is what I use now for the Motor Bridge Cape I2C functionality: https://github.com/kplindegaard/smbus2.
So, instead of using the set up of the old way listed above, use this:
#!/usr/bin/python3
# * Copyright (c) 2015 seeed technology inc.
# * Author : Jiankai Li
# * Create Time: Nov 2015
# * Change Log : Seth Dec. 2019 w/ help from #beagle at Freenode
# * and Prabakar's book called, "BealgeBone by Example."
# * license: http://www.gnu.org/licenses/gpl-3.0.txt is the license for my contributions...
# * license from Mr. Li can be found here: https://github.com/Seeed-Studio/MotorBridgeCapeforBBG_BBB/blob/master/BBG_MotorBridgeCape/MotorBridge.py (MIT).
# FileName : MotorBridge.py
# by Jiankai.li
from smbus2 import SMBus
import time
import pathlib
# reset pin is P9.23, i.e. gpio1.17
reset_pin = pathlib.Path('/sys/class/gpio/gpio49/direction')
reset_pin.write_text('low')
bus = SMBus('/dev/i2c-2')
...
Motor Bridge Cape and the BeagleBoard.org family of boards!
I am developing a python script to drive a prototype I'm developing, and my current stumbling block is attempting to continuously write to the MouseSensitivity register in Windows. I'm using Windows 7, for specificity.
Unfortunately, I've hit some dead ends.
I've attempted to use pywin32 to write to the registry, but have not succeeded. After some searching, I've come across the SystemParametersInfo Function, but have not had any success with that either.
Essentially, for the purpose of solving this crisis, I've installed pyserial, pywin32, and ctypes (it appears that pywin32 may not be required). Assume I have an integer variable that will be between (and including) 1 to 20.
What I have for code right now is listed below. Much of it has been modified from here, as it appears that the author was using python, ctypes, user32.dll, and the SystemParametersInfo Function. However, when I run the code below, the shell enters a loop where the next line gets two tabs of space, and the cursor sits blinking until I keyboard interrupt. Any ideas?
import sys
import ctypes
import ctypes.wintypes
num = 12 # Between 1 and 20
SystemParametersInfo = ctypes.windll.user32.SystemParametersInfoW
SystemParametersInfo.argtypes = (
ctypes.wintypes.UINT,
ctypes.wintypes.UINT,
ctypes.c_void_p,
ctypes.wintypes.UINT,
)
SPI_SETMOUSESPEED = 0x0071
SystemParametersInfo(SPI_SETMOUSESPEED, 0, ctypes.cast(num, ctypes.c_void_p, 0)
So I was asked to port some internal helper applications to Mac OS X 10.7.
Works all quite welll as the platform dependent code is minimal anyhow, but one application needs a system wide shortcut to function (i.e. RegisterHotkey functionality) and I can't find any documentation on how I'd do this on a Mac.
The program is using a PyQt gui with Python 3.2. and the corresponding code for windows is basically:
def register_hotkey(self):
hwnd = int(self.winId())
modifiers, key = self._get_hotkey()
user32.RegisterHotKey(hwnd, self._MESSAGE_ID, modifiers, key)
and then to receive the hotkey events:
def winEvent(self, msg):
if msg.message == w32.WM_HOTKEY:
self.handle_hotkey()
return True, id(msg)
return False, id(msg)
Note that I don't need a python variant, I can easily write a simple c extension - so C/objective-c solutions are welcome as well.
I recently coded up an extension to quodlibet capturing multimedia keys (since absorbed into quodlibet itself); for your setup the same process applies.
I used the Quartz CGEventTapCreate hook and event loop, and the Cocoa AppKit framework to decipher key codes to achieve this.
The following code registers a python callback which is passed global key presses, and starts the event loop:
import Quartz
from AppKit import NSKeyUp, NSSystemDefined, NSEvent
# Set up a tap, with type of tap, location, options and event mask
tap = Quartz.CGEventTapCreate(
Quartz.kCGSessionEventTap, # Session level is enough for our needs
Quartz.kCGHeadInsertEventTap, # Insert wherever, we do not filter
Quartz.kCGEventTapOptionListenOnly, # Listening is enough
Quartz.CGEventMaskBit(NSSystemDefined), # NSSystemDefined for media keys
keyboardTapCallback,
None
)
runLoopSource = Quartz.CFMachPortCreateRunLoopSource(None, tap, 0)
Quartz.CFRunLoopAddSource(
Quartz.CFRunLoopGetCurrent(),
runLoopSource,
Quartz.kCFRunLoopDefaultMode
)
# Enable the tap
Quartz.CGEventTapEnable(tap, True)
# and run! This won't return until we exit or are terminated.
Quartz.CFRunLoopRun()
I defined a tap for system defined keys only (media keys); you'll have to specify a different event mask (CGEventMaskBit with one or more Event Types); e.g. Quartz.CGEventMaskBit(Quartz.kCGEventKeyUp) for key up events.
The callback should have the following signature (it implements the CGEventTapCallBack method from the Quartz API:
def keyboardTapCallback(proxy, type_, event, refcon):
# Convert the Quartz CGEvent into something more useful
keyEvent = NSEvent.eventWithCGEvent_(event)
I converted the Quartz event into a NSEvent, because all the information I could find on Mac multimedia keys was referring to that class.
In principle you can achieve the same thing with the AppKit APIs too, but then your Python application is treated as a Mac Application (visible in the Dock with an icon and everything), while I wanted this to be kept in the background altogether.
Using the power of google, I found this snippet of code, which allows the registration of global hotkeys for Mac OS X
You'll need to add the Carbon framework, and probably a bridged cast for ARC when passing the Objective-C self pointer to the C function.
At a minimum, you'll also need to:
#import <Carbon/Carbon.h>
The keycodes can be seen on this page explaining the virtual key codes.
Why has nobody ever mentioned the hammerspoon, which supports custom global system shortcuts, which can invoke shell command or launch UI application like Safari, PHOTOSHOP.
The following is an example written by me demonstrating how to invoke shell function with global hotkeys.
https://gist.github.com/BigSully/0e59ab97f148bc167ea19dbd42ebef4b
Use hs.execute to execute shell command, either non-interactive or interactive.
hs.hotkey.bind({"cmd", "alt", "ctrl"}, "P", function()
local output = hs.execute("toggleProxy", true)
hs.alert.show(output)
end)
or
Use hs.application.launchOrFocus to launch application
hs.application.launchOrFocus("Safari")
I develop a critical application used by a multi-national company. Users in offices all around the globe need to be able to install this application.
The application is actually a plugin to Excel and we have an automatic installer based on Setuptools' easy_install that ensures that all a project's dependancies are automatically installed or updated any time a user switches on their Excel. It all works very elegantly as users are seldom aware of all the installation which occurs entirely in the background.
Unfortunately we are expanding and opening new offices which all have different proxy settings. These settings seem to change from day to day so we cannot keep up with the outsourced security guys who change stuff without telling us. It sucks but we just have to work around it.
I want to programatically detect the system-wide proxy settings on the Windows workstations our users run:
Everybody in the organisazation runs Windows XP and Internet Explorer. I've verified that everybody can download our stuff from IE without problems regardless of where they are int the world.
So all I need to do is detect what proxy settings IE is using and make Setuptools use those settings. Theoretically all of this information should be in the Registry.. but is there a better way to find it that is guaranteed not to change with people upgrade IE? For example is there a Windows API call I can use to discover the proxy settings?
In summary:
We use Python 2.4.4 on Windows XP
We need to detect the Internet Explorer proxy settings (e.g. host, port and Proxy type)
I'm going to use this information to dynamically re-configure easy_install so that it can download the egg files via the proxy.
UPDATE0:
I forgot one important detail: Each site has an auto-config "pac" file.
There's a key in Windows\CurrentVersion\InternetSettings\AutoConfigURL which points to a HTTP document on a local server which contains what looks like a javascript file.
The pac script is basically a series of nested if-statements which compare URLs against a regexp and then eventually return the hostname of the chosen proxy-server. The script is a single javascript function called FindProxyForURL(url, host)
The challenge is therefore to find out for any given server which proxy to use. The only 100% guaranteed way to do this is to look up the pac file and call the Javascript function from Python.
Any suggestions? Is there a more elegant way to do this?
Here's a sample that should create a bullet green (proxy enable) or red (proxy disable) in your systray
It shows how to read and write in windows registry
it uses gtk
#!/usr/bin/env python
import gobject
import gtk
from _winreg import *
class ProxyNotifier:
def __init__(self):
self.trayIcon = gtk.StatusIcon()
self.updateIcon()
#set callback on right click to on_right_click
self.trayIcon.connect('popup-menu', self.on_right_click)
gobject.timeout_add(1000, self.checkStatus)
def isProxyEnabled(self):
aReg = ConnectRegistry(None,HKEY_CURRENT_USER)
aKey = OpenKey(aReg, r"Software\Microsoft\Windows\CurrentVersion\Internet Settings")
subCount, valueCount, lastModified = QueryInfoKey(aKey)
for i in range(valueCount):
try:
n,v,t = EnumValue(aKey,i)
if n == 'ProxyEnable':
return v and True or False
except EnvironmentError:
break
CloseKey(aKey)
def invertProxyEnableState(self):
aReg = ConnectRegistry(None,HKEY_CURRENT_USER)
aKey = OpenKey(aReg, r"Software\Microsoft\Windows\CurrentVersion\Internet Settings", 0, KEY_WRITE)
if self.isProxyEnabled() :
val = 0
else:
val = 1
try:
SetValueEx(aKey,"ProxyEnable",0, REG_DWORD, val)
except EnvironmentError:
print "Encountered problems writing into the Registry..."
CloseKey(aKey)
def updateIcon(self):
if self.isProxyEnabled():
icon=gtk.STOCK_YES
else:
icon=gtk.STOCK_NO
self.trayIcon.set_from_stock(icon)
def checkStatus(self):
self.updateIcon()
return True
def on_right_click(self, data, event_button, event_time):
self.invertProxyEnableState()
self.updateIcon()
if __name__ == '__main__':
proxyNotifier = ProxyNotifier()
gtk.main()
As far as I know, In a Windows environment, if no proxy environment variables are set, proxy settings are obtained from the registry's Internet Settings section. .
Isn't it enough?
Or u can get something useful info from registry:
HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Internet Settings\ProxyServer
Edit:
sorry for don't know how to format comment's source code, I repost it here.
>>> import win32com.client
>>> js = win32com.client.Dispatch('MSScriptControl.ScriptControl')
>>> js.Language = 'JavaScript'
>>> js.AddCode('function add(a, b) {return a+b;}')
>>> js.Run('add', 1, 2)
3