I'm writing a program that runs on some lite device, like raspberry pi zero or ESP32. I hope it can act like a totp (Time-based one-time password) device, I'll set some tokens in it, and I hope it can show the dynamic password. Any help is significant to me, thanks!
this is my raw code, It works on my device, but I hope it can run in micropyhton:
import json,pyotp,time,os
t = open("./data.json","r")
dat = json.loads(t.read())
t.close()
while True:
os.system('cls')
os.system('clear')
for s in dat.keys():
print(s,pyotp.TOTP(dat[s]).now())
time.sleep(10)
data.json looks like this:
{
"<name>":"<token>",
"<name2>":"<token2>",
"<name3>":"<token3>",
....
}
I googled to find this , but I'cant find some useful solution.
Related
I'm messing around with some networking stuff and I wanted the server to be able to issue commands, namely a "stop" command. The idea was to create something similar to the minecraft server console. The issue is that when using threading, there are a few problems with just using print() and input()
Image of the Minecraft Server Console incase you dont know what I mean.
I tried to research a few things but found nothing good. I was trying to learn curses but I'm not sure how helpful it would be. I decided before I go any further I would ask on stack overflow before wasting any more time with research (I've been trying to figure this out for 2-3 days now)
Is there any simple way to do this?
I decided to go thru with learning basic curses.
I was able to make this test code and modify for my application
import curses,time
import curses.textpad
def main(screen):
h,w = screen.getmaxyx()
window = curses.newwin(h-2,w,0,0)
window.scrollok(True)
InputContainer = curses.newwin(1,w,h-1,0)
inputWindow = curses.newwin(1,w-2,h-1,2)
inputField = curses.textpad.Textbox(inputWindow,insert_mode=True)
InputContainer.addstr('> ')
window.addstr(0,0,"Console Application started\n")
screen.refresh()
InputContainer.refresh()
window.refresh()
running = True
while running:
rows, cols = screen.getmaxyx()
userIn = inputField.edit()[0:-1]
if userIn!="":
if str(userIn)=="stop":
running = False
window.addstr(f"Command Issued: {userIn}\n")
inputWindow.refresh()
inputWindow.clear()
window.refresh()
curses.wrapper(main)
Feel free to use this yourself.
I am doing a project where I have to acquire data from an Arduino Uno connected to various sensors using Python on Windows (and eventually in Raspberry Pi 2 Model B).
As Python would constantly be listening to Arduino, I was thinking how should I let Python be always ready to read in a user input (any keyboard keys or even better, with a push-button if this is possible) after which Python will tell Arduino Uno to re-acquire data from all the sensors (i.e. refresh data from the sensors) and print it on the Python Console. I am currently using PyCharm with pySerial for communications between Arduino and Python. My code (without considering user input) is as of below:
import sys
import serial
import time
arduino = serial.Serial('COM3', 9600, timeout=1)
time.sleep(3) # wait for Arduino to initialize
def readData(): # reads inputs from Arduino
try:
datastring = arduino.readline()
print datastring
except:
pass
while True:
readData()
strin = 'p'
arduino.write(strin.encode()) # tell arduino a phase shifter setting has been finished
strin = 's'
arduino.write(strin.encode())
arduino.close()
time.sleep(0.5) # waits for 0.5 s
# print('Data to be transfered: %s'%ASCIIdata)
I understand that related topics have been posted before, however, I have tried the solutions online to no avail and I am finding it quite difficult to code as I am very new to Python. (I am reading documentation and examples and trying to code at the moment.)
Currently, I have done some research on this topic and have tried the following methods but to no avail:
Using msvcrt, getch and using nodelay(1) to allow my program to run even when no user input is received. I used "stdscr", and curses, to which I used "stdscr = curses.initscr()", however, in PyCharm, as it is an IDE, it returned an error "Redirection is not supported." My attempt at implementing this is as of below:
def readData(): # reads inputs from Arduino
try:
datastring = arduino.readline()
print datastring
except:
pass
while True:
stdscr = curses.initscr()
stdscr.nodelay(1)
user_input = stdscr.getch()
if user_input == -1:
readData()
I understand there is multithreading in Python and a number of leads lead me to think that it should be the way to go if I want to listen to user inputs continuously while still acquiring data from Arduino. May I ask if this is the correct direction in which I should pursue?
I have heard about select() and poll() though the former isn't supported on Windows. I will try select() when I port my program over to Raspberry Pi which runs on Linux.
May I ask if anyone can point me to a direction on how to implement a program that reads data continuously from Arduino in PyCharm, and but a user input will cause everything to stop (like an interrupt) and have Python (PyCharm) ask Arduino to pass it a set of fresh sensor data?
Thank you! :)
I want my program to exit, whenever the device gets unplugged.
My code:
device = usb.core.find(idVendor, idProduct)
device.detach_kernel_driver(0)
usb.util.claim_interface(device, 0)
usb_cfg = device.get_active_configuration()
usb_interface = usb_cfg[(0,0)]
port_in = usb_interface[0]
port_out = usb_interface[1]
while True:
# do read ....
How can I detect an unplug of the device.
Hmmm as I looked over code on github, I would recomend to take code from this issue (I assume that You know what callbacks are :) )
PYUSB Pull request- Hotplug
In this code you use register_callback with passed event LIBUSB_HOTPLUG_EVENT_DEVICE_LEFT
EDIT 5.12.2018 :
There is a link to hotplug branch at the forked repository of the pyusb :
https://github.com/roberthartung/pyusb/tree/hotplug
I am currently trying to interface with a somewhat old old model of a HP-printer which gives me two possible methods of flow-control: No flow control at all or software-based flow control (XON/XOFF).
I am initializing pySerial with the following command and just justing a plain big string to write my data to the port:
serial = serial.Serial(port = '/dev/ttyUSB3', baudrate = 9600, parity = serial.PARITY_ODD, stopbits = serial.STOPBITS_ONE, bytesize = serial.EIGHTBITS)
This works fine - but there is a catch: it seems like the flow-control is completly ignored and data is sent and sent - which results in the device having a IO-buffer-overflow and stop working.
My first thought was, that if I use serial.write('unbelivable long string'), pySerial might not be able to cease transmission, so I split up the string into chunks and sent it:
data = ['command', 'another command', 'more commands', 'you get the drift...']
for i in data:
serial.write(i)
Well... This doesn't work either.
So basically I could just change the baud-rate to something lower so the device is faster than the transmission or just add something like a sleep every few chunks... But I guess, this is not how one should do it.
So... Anyone in to explain me, what am I doing wrong? ;-)
Thanks,
Martin
You forgot the xonxoff parameter. xonxoff=True
http://pyserial.readthedocs.io/en/latest/pyserial_api.html
Is there anyway to encorporate Dragon NaturallySpeaking into an event driven program? My boss would really like it if I used DNS to record user voice input without writing it to the screen and saving it directly to XML. I've been doing research for several days now and I can not see a way for this to happen without the (really expensive) SDK, I don't even know that it would work then.
Microsoft has the ability to write a (Python) program where it's speech recognizer can wait until it detects a speech event and then process it. It also has the handy quality of being able to suggest alternative phrases to the one that it thinks is the best guess and recording the .wav file for later use. Sample code:
spEngine = MsSpeech()
spEngine.setEventHandler(RecoEventHandler(spEngine.context))
class RecoEventHandler(SpRecoContext):
def OnRecognition(self, StreamNumber, StreamPosition, RecognitionType, Result):
res = win32com.client.Dispatch(Result)
phrase = res.PhraseInfo.GetText()
#from here I would save it as XML
# write reco phrases
altPhrases = reco.Alternates(NBEST)
for phrase in altPhrases:
nodePhrase = self.doc.createElement(TAG_PHRASE)
I can not seem to make DNS do this. The closest I can do-hickey it to is:
while keepGoing == True:
yourWords = raw_input("Your input: ")
transcript_el = createTranscript(doc, "user", yourWords)
speech_el.appendChild(transcript_el)
if yourWords == 'bye':
break
It even has the horrible side effect of making the user say "new-line" after every sentence! Not the preferred solution at all! Is there anyway to make DNS do what Microsoft Speech does?
FYI: I know the logical solution would be to simply switch to Microsoft Speech but let's assume, just for grins and giggles, that that is not an option.
UPDATE - Has anyone bought the SDK? Did you find it useful?
Solution: download Natlink - http://qh.antenna.nl/unimacro/installation/installation.html
It's not quite as flexible to use as SAPI but it covers the basics and I got almost everything that I needed out of it. Also, heads up, it and Python need to be downloaded for all users on your machine or it won't work properly and it works for every version of Python BUT 2.4.
Documentation for all supported commands is found under C:\NatLink\NatLink\MiscScripts\natlink.txt after you download it. It's under all the updates at the top of the file.
Example code:
#make sure DNS is running before you start
if not natlink.isNatSpeakRunning():
raiseError('must start up Dragon NaturallySpeaking first!')
shutdownServer()
return
#connect to natlink and load the grammer it's supposed to recognize
natlink.natConnect()
loggerGrammar = LoggerGrammar()
loggerGrammar.initialize()
if natlink.getMicState() == 'off':
natlink.setMicState('on')
userName = 'Danni'
natlink.openUser(userName)
#natlink.waitForSpeech() continuous loop waiting for input.
#Results are sent to gotResultsObject method of the logger grammar
natlink.waitForSpeech()
natlink.natDisconnect()
The code's severely abbreviated from my production version but I hope you get the idea. Only problem now is that I still have to returned to the mini-window natlink.waitForSpeech() creates to click 'close' before I can exit the program safely. A way to signal the window to close from python without using the timeout parameter would be fantastic.