how to use INPUT_PULLUP using pyfirmata2 - python

In Arduino IDE (C++ programming language) we can use pinMode(button, INPUT_PULLUP) to avoid using resistor, but here I'm using Arduino microcontroller and running StandardFirmata inside it, then I use python and pyfirmata library but I don't know how to call INPUT_PULLUP, and if I run the program the output will be true and false.
from pyfirmata2 import Arduino, util
import time
board = Arduino('COM6')
iterator = util.Iterator(board)
iterator.start()
button = board.get_pin('d:2:i')
while True:
print(button.read())
time.sleep(1)

I don't believe that pyfirmata supports pullup. You can try Telemetrix Telemetrix is similar to Firmata, but does not use 7bit bytes. You can view its API here. If you really need to use Firmata, then also look at pymata4.

Related

How to assign a 2d libreoffice calc named range to a python variable. Can do it in Libreoffice Basic

I can't seem to find a simple answer to the question. I have this successfully working in Libreoffice Basic:
NamedRange = ThisComponent.NamedRanges.getByName("transactions_detail")
RefCells = NamedRange.getReferredCells()
Set MainRange = RefCells.getDataArray()
Then I iterate over MainRange and pull out the rows I am interested in.
Can I do something similar in a python macro? Can I assign a 2d named range to a python variable or do I have to iterate over the range to assign the individual cells?
I am new to python but hope to convert my iteration intensive macro function to python in hopes of making it faster.
Any help would be much appreciated.
Thanks.
LibreOffice can be manipulated from Python with the library pyuno. The documentation of pyuno is unfortunately incomplete but going through this tutorial may help.
To get started:
Python-Uno, the library to communicate via Uno, is already in the LibreOffice Python’s path. To initialize your context, type the following lines in your python shell :
import socket # only needed on win32-OOo3.0.0
import uno
# get the uno component context from the PyUNO runtime
localContext = uno.getComponentContext()
# create the UnoUrlResolver
resolver = localContext.ServiceManager.createInstanceWithContext(
"com.sun.star.bridge.UnoUrlResolver", localContext )
# connect to the running office
ctx = resolver.resolve( "uno:socket,host=localhost,port=2002;urp;StarOffice.ComponentContext" )
smgr = ctx.ServiceManager
# get the central desktop object
desktop = smgr.createInstanceWithContext( "com.sun.star.frame.Desktop",ctx)
# access the current writer document
model = desktop.getCurrentComponent()
Then to get a named range and access the data as an array, you can use the following methods:
NamedRange = model.NamedRanges.getByName(“Test Name”)
MainRange = NamedRange.getDataArray()
However I am unsure that this will result in a noticeable preformance gain.

How do I send a message from python to C++

I'm trying to get an example of openFramworks (C++) and python to work together, thus far, following an example I've been able to call python fucntion from C++ in the follwoing manner
ofxPythonObject klass = python.getObject("myApp");
if(klass)
python_program = klass();
python_program.method("subscribe");
The interface uses swig under the hood, I'm wondering how do I send a message back to C++ from python, is this even possible?
I don't know if it's possible through SWIG, but you could use a PUB\SUB from python to C. Might be overkill and just a suggestion, and one that I would have left in your comments had my score been adequate.
#publish in Python
import zmq
context = zmq.Context()
socket = context.socket(zmq.PUB)
socket.bind("tcp://*:5556")
+++++++++++++++++++++++++++++++++++++++++++++++
# receive in C
include <zmq.hpp>
zmq::socket_t subscriber (context, ZMQ_SUB);
subscriber.connect("tcp://localhost:5556");
Good luck.

Python network bandwidth monitor

I am developing a program in python, and one element tells the user how much bandwidth they have used since the program has opened (not just within the program, but regular web browsing while the program has been opened). The output should be displayed in GTK
Is there anything in existence, if not can you point me in the right direction. It seems like i would have to edit an existing proxy script like pythonproxy, but i can't see how i would use it.
Thanks,
For my task I wrote very simple solution using psutil:
import time
import psutil
def main():
old_value = 0
while True:
new_value = psutil.net_io_counters().bytes_sent + psutil.net_io_counters().bytes_recv
if old_value:
send_stat(new_value - old_value)
old_value = new_value
time.sleep(1)
def convert_to_gbit(value):
return value/1024./1024./1024.*8
def send_stat(value):
print ("%0.3f" % convert_to_gbit(value))
main()
import time
def get_bytes(t, iface='wlan0'):
with open('/sys/class/net/' + iface + '/statistics/' + t + '_bytes', 'r') as f:
data = f.read();
return int(data)
while(True):
tx1 = get_bytes('tx')
rx1 = get_bytes('rx')
time.sleep(1)
tx2 = get_bytes('tx')
rx2 = get_bytes('rx')
tx_speed = round((tx2 - tx1)/1000000.0, 4)
rx_speed = round((rx2 - rx1)/1000000.0, 4)
print("TX: %fMbps RX: %fMbps") % (tx_speed, rx_speed)
should be work
Well, not quiet sure if there is something in existence (written in python) but you may want to have a look at the following.
Bandwidth Monitoring (Not really an active project but may give you an idea).
Munin Monitoring (A pearl based Network Monitoring Project)
ntop (written in C/C++, based on libpcap)
Also just to give you pointers if you are looking to do something on your own, one way could be to count and store packets using sudo cat /proc/net/dev
A proxy would only cover network applications that were configured to use it. You could set, e.g. a web browser to use a proxy, but what happens when your proxy exits?
I think the best thing to do is to hook in lower down the stack. There is a program that does this already, iftop. http://en.wikipedia.org/wiki/Iftop
You could start by reading the source code of iftop, perhaps wrap that into a Python C extension. Or rewrite iftop to log data to disk and read it from Python.
Would something like WireShark (https://wiki.wireshark.org/FrontPage) do the trick? I am tackling a similar problem now, and am inclined to use pyshark, a WireShark/TShark wrapper, for the task. That way you can get capture file info readily.

How can I send keys to a game I am playing,using python?

I am playing deus ex human revolution,and there are things you can access with the correct 4 digit code.
I was wondering if you could make a script to brute force it sending keystrokes to the game.
I have tried using send keys but i could not make it work.Any ideas?Thanks.
Python:
-SendKeys
This is what I have tried,which I found here:
import win32com.client
import time
import SendKeys
import os
from ctypes import *
shell = win32com.client.Dispatch("WScript.Shell")
os.startfile('C:\\....exe')
time.sleep( 150 )
shell.SendKeys('1')
The way I am trying at first is open the game with the script,put a time delay to load the save game,and I open a terminal to hack it, but the key is not send.
-pywinauto:
Using pywinauto I have this:
from pywinauto import application
import time
app=application.Application()
app.connect_(title_re = "Deus Ex: Human Revolution - The Missing Link", class_name = "DeusExHRE")
Now I am searching which dialogs are available.
AutoHotKeys:
So except from python,I am trying with AutoHotKeys:
This works:
SetKeyDelay 180
F12::
Send {0 down}
Send {0 up}
Send {0 down}
Send {0 up}
Send {0 down}
Send {0 up}
Send {0 down}
Send {0 up}
Send {Backspace down}
Send {Backspace up}
Return
The keydelay is the minimum I found that didn't miss any buttons.I am looking for a way to make it faster,maybe by using a different send method.
Updated:
-pywinauto
-autohotkeys
Have you ever tried this ?
You've probably already thought of this but just in case, make sure you try your solution(s) in a couple of places. IIRC, there's a couple of spots in Deus Ex where you have to discover the code in-game before you can use it, even though the code itself is hard-wired into the game.
What'd be really cool is if you got something to do the hacking mini-games automatically. :)
Some years late, but answering anyway as other might face the same problem like I did...
In Windows you can use win32api to send keys to the active application, but you have to give it a scan code also to make it work in some types of applications such as games
To send a single key, you must have it's virtual key code that you can get either by
using the solution Here or by having a dictionary (that you can easily find done in google or make it yourself)
MapVirtualKey
keybd_event
import win32api, win32con, time
# in this example i'm using a dictionary (that i called VK_CODE)
# to map the keys to their respective virtual key codes
# Sending the key a
i = 'a'
# send key down event
win32api.keybd_event(VK_CODE[i], win32api.MapVirtualKey(VK_CODE[i], 0), 0, 0)
# wait for it to get registered.
# You might need to increase this time for some applications
time.sleep(.05)
# send key up event
win32api.keybd_event(VK_CODE[i], win32api.MapVirtualKey(VK_CODE[i], 0), win32con.KEYEVENTF_KEYUP, 0)

Modules or functions to obtain information from a network interface in Python

I wrote a little application that I use from the terminal in Linux to keep track of the amount of data up and down that I consume in a session of Internet connection (I store the info in MongoDB). The data up and down I write by hand and read them (visually) from the monitor system, the fact is that I would like to automate more my application and make it read data consumed up and down from the interface network i use to connect to internet (in my case ppp0), but the detail is in that I does not find the way to do in Python. I guess Python have a module to import or something that lets me do what I want, but until now I have researched I have not found a way to do it.
Do you know of any module, function or similar that allows me to do in python what I want?
any example?
thanks in advance
Well I answer myself
Found in the community PyAr this recipe to me me like a glove going to do what we wanted without having to use extra commands or other applications.
Slightly modifying the code to better suit my application and add a function that comvierta of bytes to Megabytes leave it like this:
def bytestomb(b):
mb = float(b) / (1024*1024)
return mb
def bytessubidatransferidos():
interface= 'ppp0'
for line in open('/proc/net/dev', 'r'):
if interface in line:
data = line.split('%s:' % interface)[1].split()
tx_bytes = (data[8])
return bytestomb(tx_bytes)
def bytesbajadatransferidos():
interface= 'ppp0'
for line in open('/proc/net/dev', 'r'):
if interface in line:
data = line.split('%s:' % interface)[1].split()
rx_bytes = (data[0])
return bytestomb(rx_bytes)
print bytessubidatransferidos()
print bytesbajadatransferidos()

Categories

Resources