NameError Using time.sleep in MicroPython - python

import time
from umqtt.simple import MQTTClient
from machine import Pin
from dht import DHT22
SERVER = 'X.X.X.X' # MQTT Server Address (Change to the IP address of your Pi)
CLIENT_ID = 'ESP32_DHT22_Sensor'
TOPIC = b'temp_humidity'
running = True
client = MQTTClient(CLIENT_ID, SERVER)
client.connect() # Connect to MQTT broker
sensor = DHT22(Pin(15, Pin.IN, Pin.PULL_UP)) # DHT-22 on GPIO 15 (input with internal pull-up resistor)
def run():
while running:
try:
sensor.measure() # Poll sensor
t = sensor.temperature()
h = sensor.humidity()
tm = time.localtime(time.time())
if isinstance(t, float) and isinstance(h, float) and tm[0] > 2000: # Confirm sensor results$
msg = (b'{0:n},{1:n},{2:n},{3:n},{4:n},{5:3.1f},{6:3.1f}'.format(tm[0], tm[1], tm[2]$
client.publish(TOPIC, msg, retain=True) # Publish sensor data to MQTT topic
print(str(msg))
print('Sent to ' + SERVER + ' as ' + CLIENT_ID + '. Exiting.')
running = False
else:
print('Invalid sensor readings.')
except OSError:
print('Failed to read sensor.')
time.sleep(1)
Apologies for importing the whole script. As it is short, I thought it may be valuable to be able to see all of it. I import time at the top of the script and as far as I can tell, all variables are referenced before they are used.
I would like to import this script as dht_publish and then run dht_publish.run(). However, this gives the following error. This is run on the latest MicroPython binary on an ESP32 dev board.
Traceback (most recent call last):
File <stdin>, line 1, in <module>
File dht_publish.py, line 33, in run
NameError: local variable referenced before assignment
If I comment out the time.sleep(1) line then the error is flagged on the line before which suggests that the error may be elsewhere in the code but I can't see where. Any help on this would be very much appreciated.

In case anyone is trying something similar and runs up against the same issue, the problem was that the running variable within the run function was looking up a local variable. Moving the definition of the running variable to the first line after def run(): solved the issue.

Related

Set esp32 access point web server using Micropython

I am trying to run a mini web server on my ESP32 feather huzzah32, but I hit an error every time I try to open the console. I tried several times, updated everything, erased the flash also few time to start over and the same.
The line 37 seems to have a problem I cannot figure out.
When I am done with compiling and upload the code, I see this error:
(IOError #[0047:0013:0000:0048:0000:0000:0000:0000]
oops, something wrong while linkin:
(IOError at line 37 of main raised at line 97 of wireless.wifi.link
Here is my code.
import streams
import socket
from wireless import wifi
from espressif.esp32net import esp32wifi as wifi_driver
streams.serial()
wifi_driver.auto_init()
wifi.link("my-ssid",wifi.WIFI_WPA2,"my-password")
except Exception as e:
print("ooops, something wrong while linking :(", e)
while True:
sleep(1000)
print("Linked!")
info = wifi.link_info()
print("My IP is:",info[0])
sock = socket.socket()
sock.bind(80)
sock.listen()
while True:
try:
client = streams.SocketStream(clientsock)
line = client.readline()
while line!="\n" and line!="\r\n":
line = client.readline()
print("HTTP request received!")
print("HTTP/1.1 200 OK\r",stream=client)
print("Content-Type: text/html\r",stream=client)
print("Connection: close\r\n\r",stream=client)
print("<html><body>Hello Zerynth!",random(0,100),"</body></html>",stream=client)
client.close()
except Exception as e:
print("ooops, something wrong:",e)
I am using Zerynth.
Any ideas?
I found the issue. It was a bit silly but often errors are indeed silly. Istead of using routers SSID, I tried with the name of the WIFI network and it worked just fine. There is the code, line 37.
wifi.link("NAME_OF_THE_NETWORK",wifi.WIFI_WPA2,"NETWORK_PASSWORD")

Facebook Thrift SSH Frame Size Error

I am running the Facebook Thrift service on my machine. I used a sample code to show its working:
import asyncio
from fbnet.command_runner.thrift_client import AsyncioThriftClient
# Import FCR Thrift Types
from fbnet.command_runner_asyncio.CommandRunner import ttypes as fcr_ttypes
# Import FCR Service Client
from fbnet.command_runner_asyncio.CommandRunner.Command import Client as FcrClient
import getpass
# Device Information
hostname = 'my_vm'
username = 'root'
password = getpass.getpass('%s Password: ' % username)
# Destination device
device = fcr_ttypes.Device(hostname=hostname, username=username, password=password)
async def run(cmd, device):
async with AsyncioThriftClient(FcrClient, 'x.x.x.x',22 ) as client:
res = await client.run(cmd, device)
# type of res is `struct CommandResult`
print(res.output)
loop = asyncio.get_event_loop()
loop.run_until_complete(run('uname -a', device))
However I am getting the following error:
Frame size 1397966893 too large for THeaderProtocol Traceback (most
recent call last):
File "pgm1.py", line 28, in
loop.run_until_complete(run('uname -a', device))
File "/usr/local/lib/python3.6/asyncio/base_events.py", line 467, in run_until_complete
return future.result()
File "pgm1.py", line 23, in run
res = await client.run(cmd, device) thrift.transport.TTransport.TTransportException: Connection closed
Any ideas on how to correct this?
#Kenster's comment indicates the real problem here.
0x5353482D is the four characters "SSH-", which happens to be the first data sent by an ssh server when something connects to it
There are some server implementations that require TFramedProtocol by design. In other words, it is mandatory, the client has to use it, simply because the server expects it that way.
The insight comes quickly to one who knows that TFramedProtocol adds a 4 byte header carrying the frame size of the data to follow. If the client does not use TFramedProtocol, the server will interpret the first four databytes as the frame size - hence the error message.
Solution
Add TFramedProtocol on the client side to the Thrift transport/protocol stack.

For bluetooth connection using PyBluez, socket connection is not getting accepted even after pairing

I have a Raspberry pi model B booted with Rasbian OS and a bluetooth dongle plugged into it. I am able to discover my pi when searching from my PC and am able to pair using Blueman GUI. This is the python program I am using for the pairing process:
from bluetooth import *
server_sock=BluetoothSocket(L2CAP)
server_sock.bind(("", 17))
with open(sys.path[0] + "/sdp_record.xml", "r") as fh:
service_record = fh.read()
self.bus = dbus.SystemBus()
self.manager = dbus.Interface(self.bus.get_object("org.bluez", "/"),"org.bluez.Manager")
adapter_path = self.manager.DefaultAdapter()
self.service = dbus.Interface(self.bus.get_object("org.bluez",adapter_path),
"org.bluez.Service")
service_handle = service.AddRecord(service_record)
print "Service record added"
server_sock.listen(1)
print("Waiting for connection on L2CAP")
try:
client_sock, client_info = server_sock.accept()
print("Accepted connection from ", client_info)
while True:
data = client_sock.recv(1024)
if len(data) == 0:
break
print("received [%s]" % data)
except IOError:
pass
except KeyboardInterrupt:
print "Stopping..."
stop_advertising(server_sock)
sys.exit()
print("disconnected")
client_sock.close()
server_sock.close()
print("all done")
I already have a working SDP record, which is being read and it is added to the SDP server.
At first when I posted this question I got this error:
Traceback (most recent call last):
File "pytest.py", line 4, in <module>
server_sock.bind(("", 17))
File "/usr/lib/python2.7/dist-packages/bluetooth/bluez.py", line 140, in bind
return self._sock.bind (addrport)
_bluetooth.error: (13, 'Permission denied')
This is because bluetooth needs root privileges. I ran the python code using sudo python code.py and this error was resolved. Thanks very much to guys who answered.
Now the problem I get is, the socket connection is not getting accepted even after pairing. For pairing, I run the code in one terminal and when it is waiting for connection on L2CAP, I open another console and pair the pi with my computer using the command sudo bluez-simple-agent hci0 computers_macaddress, it is getting paired after entering a pin in both the pi and computer. But after the pairing, the code is still waiting for connection:
Service record added
Waiting for connection on L2CAP
It seems to be looping at that server_sock.accept() function.
Can anyone give a solution?
I also faced the same kind of issue. The problem was with the operating power of the pi. USB ports usually provide only 500 mA, 5 V. Raspberry pi need a voltage source of about 4.75 to 5.25V and current in range of 700 to 1000 mA for optimum performance. Exactly how much current (mA) the Raspberry Pi requires is dependent on what you connect to it. Try changing the source, fetch power via a 1000 mA 5v adapter.
Let me know if it worked.

Python Socket Programming: Application freezes when connecting to a server

I am new to socket coding in Python, and I wrote this simple function to connect to a server. It runs in a tkinter window. I have an Entry widget, and it is where you input the IP address of the server to connect to. However, when you click the button to connect, the application hangs and freezes. Here is the code below.
def Test(self):
socket.setdefaulttimeout(5)
lengthInfo = self.lengthEntry.get()
if self.portEntry.get() != '':
portInfo = int(self.portEntry.get())
serverInfo = self.serverEntry.get()
conn = socket.socket()
if not self.portEntry.get():
portInfo = 80
try:
conn = socket.socket()
name = socket.gethostbyname(serverInfo)
conn.connect((name,portInfo))
ans = conn.recv(2048)
self.outputWindow.insert(END, "Connection successful: \n \
port:{}, server:{} ('{}'), '{}' \n".format(portInfo, name, serverInfo, \
ans))
return
except Exception as e:
self.outputWindow.insert(END, str(e) + "\n")
I originally thought it was because there was now timeout, but as you can see, I added a 5 second timeout in the very first line of the code. I assumed it was because the application was having some sort of trouble connecting, but I checked Windows task manager, and under the network section there was no activity. I also ran the program in Ubuntu 14.04 but got the same results.
Any solutions?
The socket waits for 2,048 bytes from the server (conn.recv(2048)) and I guess they never arrive.

Trying to create a Python Server

I am looking at trying to create a python server, which allows me to run root commands on a Centos Server remotely, I would also like the server to be able to respond with the result's of the command.
I have found another question on here which has a basic python server, however it throws a error, the code is:
#!/usr/bin/python
import os
import socket
print " Loading Bindings..."
settings = {}
line = 0
for each in open('/root/actions.txt', 'r'):
line = line + 1
each = each.rstrip()
if each <> "":
if each[0] <> '#':
a = each.partition(':')
if a[2]:
settings[a[0]] = a[2]
else:
print " Err # line",line,":",each
print " Starting Server...",
port = 12345
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.bind(("", port))
print "OK."
print " Listening on port:", port
while True:
datagram = s.recv(1024)
if not datagram:
break
print "Rx Cmd:", datagram
if settings.has_key(datagram):
print "Launch:", settings[datagram]
os.system(settings[datagram]+" &")
s.close()
When i run using python vzctl.py. I get the following error:
File "vzctl.py", line 9
each = each.rstrip()
^
SyntaxError: invalid syntax
Does anyone have any idea of the error, and if it would be possible to add the function of the server responding with the output of the command.
You can see the source of this script at : How can I have a PHP script run a shell script as root?
Thanks,
Ashley
you need to keep indentation at the same level for each nested statement throughout your code.
On a different note: why not using TwistedMatrix?

Categories