Skip to content

Commit

Permalink
Screens for AD
Browse files Browse the repository at this point in the history
  • Loading branch information
IhorNehrutsa committed Aug 14, 2023
1 parent 0fa4968 commit 10ece1b
Show file tree
Hide file tree
Showing 17 changed files with 375 additions and 1,054 deletions.
61 changes: 29 additions & 32 deletions ports/esp32/modules/WiFi.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,15 +25,11 @@
ATTEMPTS = 30 # ATTEMPTS * CONNECTING_PAUSE_S = 30 * 1 = 30s

wlan_ap = WLAN(AP_IF)
wlan_sta = WLAN(STA_IF)


def WiFi_sta():
return WLAN(STA_IF)
wlan_st = WLAN(STA_IF)


def WiFi_sta_stop():
wlan = WiFi_sta()
wlan = WLAN(STA_IF)
try:
wlan.disconnect()
except:
Expand All @@ -50,19 +46,19 @@ def save_config_WiFi(ssid, password, ifconfig):
try:
print("Save './config_WiFi.py'")
with open("./config_WiFi.py", "w") as f:
f.write("SSID = '{}'\n".format(ssid))
f.write("PASSWORD = '{}'\n".format(password))
f.write("OWL_IP = '{}'\n".format(ifconfig[0]))
f.write("OWL_SUBNET = '{}'\n".format(ifconfig[1]))
f.write("OWL_GATEWAY = '{}'\n".format(ifconfig[2]))
f.write("OWL_DNS = '{}'\n".format(ifconfig[3]))
f.write(f"SSID = '{ssid}'\n")
f.write(f"PASSWORD = '{password}'\n")
f.write(f"OWL_IP = '{ifconfig[0]}'\n")
f.write(f"OWL_SUBNET = '{ifconfig[1]}'\n")
f.write(f"OWL_GATEWAY = '{ifconfig[2]}'\n")
f.write(f"OWL_DNS = '{ifconfig[3]}'\n")
f.close()
except BaseException as e:
print_exception(e)
print('Error writing config_WiFi.py')

def WiFi_check_before(ssid, password, ip="192.168.4.1", subnet="255.255.255.0", gateway="192.168.4.1", dns="0.0.0.0"):
wlan = WiFi_sta()
wlan = WLAN(STA_IF)
wlan.active(True)
ifconfig = wlan.ifconfig()
wlan_isconnected = wlan.isconnected()
Expand All @@ -72,19 +68,19 @@ def WiFi_check_before(ssid, password, ip="192.168.4.1", subnet="255.255.255.0",
wlan.disconnect()
idle() # save power while waiting
sleep_ms(200)
print("WiFi disconnected form SSID:{}".format(wlan.config('essid')))
print(f"WiFi disconnected form SSID:{wlan.config('essid')})")
wlan_isconnected = False
elif ifconfig != (ip, subnet, gateway, dns):
while wlan.isconnected():
wlan.disconnect()
idle() # save power while waiting
sleep_ms(200)
print("WiFi disconnected because:\n{} != \n{}".format(ifconfig, (ip, subnet, gateway, dns)))
print(f"WiFi disconnected because:\n{ifconfig} != \n{(ip, subnet, gateway, dns)})")
wlan_isconnected = False
return wlan_isconnected

def WiFi_check_after(wlan_isconnected, ssid, password, ip="192.168.4.1", subnet="255.255.255.0", gateway="192.168.4.1", dns="0.0.0.0"):
wlan = WiFi_sta()
wlan = WLAN(STA_IF)
wlan.active(True)
if wlan.isconnected():
wlan_ap.active(False)
Expand All @@ -104,7 +100,7 @@ def WiFi_check_after(wlan_isconnected, ssid, password, ip="192.168.4.1", subnet=
if not wlan_isconnected:
print()
print('ESP mac:', hexlify(wlan.config('mac'), ':').decode("utf-8").upper())
print("Connected to WiFi '{}'".format(ssid))
print(f"Connected to WiFi '{ssid}'")
print("wlan.ifconfig():", wlan.ifconfig())
try:
print("wlan.status('rssi')", rssi(wlan.status('rssi')))
Expand All @@ -125,11 +121,11 @@ def WiFi_check_after(wlan_isconnected, ssid, password, ip="192.168.4.1", subnet=
save_config_WiFi(ssid, password, ifconfig)

def WiFi_login(ssid, password, ip="192.168.4.1", subnet="255.255.255.0", gateway="192.168.4.1", dns="0.0.0.0"):
""" Enable station interface and connect to WiFi access point """
wlan = WiFi_sta()
# Enable station interface and connect to WiFi access point
wlan = WLAN(STA_IF)
wlan.active(True)
if not wlan.isconnected():
# print("Connecting to network '{}'".format(ssid))
# print("Connecting to network '{ssid}'")
# wlan.config(reconnects=10)
if ip == 'dhcp':
wlan.ifconfig(('dhcp'))
Expand All @@ -151,15 +147,16 @@ def WiFi_while(ssid, password, ip="192.168.4.1", subnet="255.255.255.0", gateway
wlan_isconnected = WiFi_check_before(ssid, password, ip, subnet, gateway, dns)
i = 0
t = 0
wlan = WiFi_sta()
wlan = WLAN(STA_IF)
while (wlan.status() != 1010) and (i < ATTEMPTS):
if ticks_diff(ticks_ms(), t) > CONNECTING_PAUSE_S * 1000:
i += 1
print()
print("Connecting to network '{}'".format(ssid))
print("ifconfig:", (ip, subnet, gateway, dns))
print(f"Connecting to network '{ssid}'")
#print("ifconfig:", (ip, subnet, gateway, dns))
print("ifconfig:", wlan.ifconfig())
print("wlan.status():", wlan_status(wlan.status()), end ='')
print(" : WiFi connecting timeout is {} seconds, attempt {} of {}.".format(CONNECTING_PAUSE_S, i, ATTEMPTS))
print(f" : WiFi connecting timeout is {CONNECTING_PAUSE_S} seconds, attempt {i} of {ATTEMPTS}.)")
t = ticks_ms()

WiFi_login(ssid, password, ip, subnet, gateway, dns)
Expand All @@ -171,18 +168,18 @@ def WiFi_while(ssid, password, ip="192.168.4.1", subnet="255.255.255.0", gateway

if not wlan.isconnected():
wlan.active(False) # перестраховка
print("Can not connect to the WiFi '{}'".format(ssid))
print(f"Can not connect to the WiFi '{ssid}'")
wlan = wlan_ap
wlan.active(True)
#wlan_ap.config(essid=ap_ssid, password=ap_password, authmode=ap_authmode)
ssid = wlan.config('essid')
print("Starting as access point '{}'".format(ssid))
print(f"Starting as access point '{ssid}'")
# wait_connection(ssid)

return wlan

def WiFi_start():
""" Set login parameter here """
# Set login parameter here
try:
import config_WiFi
SSID = config_WiFi.SSID
Expand Down Expand Up @@ -210,19 +207,19 @@ def host(host=""):
# ===============================================================================
if __name__ == "__main__":
print("WiFi:")
print('AP: active()={}, isconnected()={}, status={}, ifconfig={}'.format(wlan_ap.active(), wlan_ap.isconnected(), wlan_status(wlan_ap.status()), wlan_ap.ifconfig()))
print('STA: active()={}, isconnected()={}, status={}, ifconfig={}'.format(wlan_sta.active(), wlan_sta.isconnected(), wlan_status(wlan_sta.status()), wlan_sta.ifconfig()))
print(f'AP: active()={wlan_ap.active()}, isconnected()={wlan_ap.isconnected()}, status={wlan_status(wlan_ap.status())}, ifconfig={wlan_ap.ifconfig()}')
print(f'STA: active()={wlan_st.active()}, isconnected()={wlan_st.isconnected()}, status={wlan_status(wlan_st.status())}, ifconfig={wlan_st.ifconfig()}')

#wlan = WiFi_sta_stop()

wlan = WiFi_start()
if wlan_sta.active():
if wlan_st.active():
print()
print("WiFi scan()...")
wireless_networks = wlan.scan()
if len(wireless_networks):
print("wlan.scan(): (ssid, bssid, channel, rssi(dBm), authmode, hidden)")
for e in wireless_networks:
print(e, end='')
print("| RSSI={}dBm:{} | authmode={}".format(e[3], rssi(e[3]), authmode(e[4])))
#print("| bssid='{}' | RSSI={}dBm:{} | authmode={}".format(hexlify(e[1]).decode("utf-8"), e[3], rssi(e[3]), authmode(e[4])))
print(f"| RSSI={e[3]}dBm:{rssi(e[3])} | authmode={authmode(e[4])}")
print(f"| bssid='{e[1]).decode("utf-8")}' | RSSI={hexlify(e[3]}dBm:{rssi(e[3])} | authmode={authmode(e[4])}")

Check failure on line 225 in ports/esp32/modules/WiFi.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (E999)

ports/esp32/modules/WiFi.py:225:45: E999 SyntaxError: Unexpected token 'utf'
34 changes: 20 additions & 14 deletions ports/esp32/modules/coord.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
class Coordinate():
def __init__(self, mover, max_search=180, min_search=-180):
""" Constructor """
self.mover = mover
# self.circle_diagram = [0 for i in range(360)]
self.circle_diagram = 0 # {ros_param: [0 for i in range(int(360/angle_resolution))] for ros_param in ros_params}
Expand All @@ -25,7 +24,6 @@ def __init__(self, mover, max_search=180, min_search=-180):
self.value_minus = {} # значение в конце поиска в "отрицательном" направлении

self.angle_best = None
self.value_best = {} # лучшее значение в процессе поиска
self.avg_best = {} # среднее значение в лучшей позиции

self.angle_bisector_diff = None # угол посередине участка плато
Expand All @@ -39,6 +37,9 @@ def __init__(self, mover, max_search=180, min_search=-180):
self.max_search = max_search # сектор поиска заданный оператором должен быть уже, чем физические механические ограничения конструкции
self.min_search = min_search

def __repr__(self):
return f"Coordinate({super().__repr__()}, max_search={self.max_search}, min_search={self.min_search})"

def correct_handler(self, delta_angle):
def to180(a):
return a
Expand All @@ -64,7 +65,7 @@ def to180(a):

# -----------------------------------------------------------------------
def on_correct(self, handler):
""" Set correction handler """
# Set correction handler
self._on_correct_handler = handler

def correct_angles(self, delta_angle):
Expand All @@ -85,17 +86,22 @@ def set_angle_start(self, angle):

class CoordinateShow(Coordinate):
def __init__(self, mover, max_search=180, min_search=-180):
""" Constructor """
super().__init__(mover, max_search, min_search)

@property
def target(self):
return self.mover.target

@target.setter
def target(self, to_angle):
self.mover.target = to_angle
if self.search_dir > 0:
print('+++', self.mover.name, to_angle)
else:
print('---', self.mover.name, to_angle)
def angle_target(self):
#print(f'{self.mover.name} CoordinateShow():angle_target.property')
return self.mover.angle_target

@angle_target.setter
def angle_target(self, angle_target):
#print(f'{self.mover.name} CoordinateShow():angle_target.setter')
#print(f'{self.mover.name} CoordinateShow():angle_target.setter self.mover.angle_target={self.mover.angle_target} self.max_search={self.max_search}')
if self.mover.angle_target != angle_target:
self.mover.angle_target = max(min(angle_target, self.max_search), self.min_search)
# if self.mover.angle_now < self.mover.angle_target:
# print('+++', self.mover.name, self.mover.angle_target)
# else:
# print('---', self.mover.name, self.mover.angle_target)
#print(f'self.mover={self.mover}')
#print(f'{self.mover.name} CoordinateShow():angle_target.setter self.mover.angle_target={self.mover.angle_target} self.max_search={self.max_search}')
22 changes: 10 additions & 12 deletions ports/esp32/modules/microPyServer.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,6 @@

class MicroPyServer(object):
def __init__(self, host="", port=80, cargo=None):
""" Constructor """
self.host = host
self.port = port

Expand Down Expand Up @@ -68,11 +67,10 @@ def empty_bufs(self):
self.empty_out_buf()

def __del__(self):
""" Destructor """ # Special method __del__ not implemented for user-defined classes in MicroPython !!!
self.end()

def find_route(self, request):
""" Find route """
# Find route
line0 = request.split(b"\r\n")[0]
method = _method_regexp.search(line0).group(1)
path = _path_regexp.search(line0).group(1)
Expand All @@ -84,11 +82,11 @@ def find_route(self, request):
return None, arg

def find_route_txt(self, path):
""" Find route txt """
# Find route txt
return self._routes[path + b'\x00GET']

def begin(self):
""" Call it before the main loop """
# Call it before the main loop
try:
self._socket = open_server_socket(self.host, self.port, backlog=_BACKLOG)
print("{}:{} MicroPyServer started".format(self.host, self.port))
Expand Down Expand Up @@ -175,7 +173,7 @@ def send(self, do_close):
self.connect_close()

def execute(self):
""" Call it in the main loop """
# Call it in the main loop
if self._socket is None:
if self.begin() is None:
return
Expand Down Expand Up @@ -203,7 +201,7 @@ def execute(self):
self.send(True)

def add_route(self, path, handler, method="GET"):
""" Add new route """
# Add new route
self._routes.update({path.encode() + b'\x00' + method.encode(): handler})

def connection_send(self, buf):
Expand All @@ -219,7 +217,7 @@ def connection_send(self, buf):
}

def out(self, response, status=200, content_type="Content-Type: text/html", extra_headers=None):
""" Send response to client """
# Send response to client
'''
### speed optimized
self.connection_send("HTTP/1.0 {:d} {:s}\r\n{:s}\r\n".format(status, self.status_message[status], content_type))
Expand All @@ -238,11 +236,11 @@ def out(self, response, status=200, content_type="Content-Type: text/html", extr
self.connection_send(response)

def not_found(self):
""" Not found action """
# Not found action
self.out("404", status=404, content_type="Content-Type: text/plain")

def internal_error(self, error):
""" Catch error action """
# Catch error action
output = StringIO()
#print_exception(error, output)
str_error = output.getvalue()
Expand All @@ -253,11 +251,11 @@ def internal_error(self, error):
pass

#def on_request(self, handler):
# """ Set request handler """
# # Set request handler
# self._on_request_handler = handler

def execute_txt(self):
""" Call it in the main loop """
# Call it in the main loop
if self._socket is None:
if self.begin() is None:
return
Expand Down
26 changes: 9 additions & 17 deletions ports/esp32/modules/mpu6500.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,9 +19,7 @@
# SOFTWARE.

# https://github.com/tuupola/micropython-mpu9250
"""
MicroPython I2C driver for MPU6500 6-axis motion tracking device
"""
# MicroPython I2C driver for MPU6500 6-axis motion tracking device

__version__ = "0.3.0"

Expand Down Expand Up @@ -98,7 +96,7 @@


class MPU6500:
"""Class which provides interface to MPU6500 6-axis motion tracking device."""
# Class which provides interface to MPU6500 6-axis motion tracking device.
def __init__(
self,
i2c,
Expand Down Expand Up @@ -129,12 +127,10 @@ def __repr__(self):

@property
def acceleration(self):
"""
Acceleration measured by the sensor. By default will return a
3-tuple of X, Y, Z axis acceleration values in m/s^2 as floats. Will
return values in g if constructor was provided `accel_sf=SF_M_S2`
parameter.
"""
# Acceleration measured by the sensor. By default will return a
# 3-tuple of X, Y, Z axis acceleration values in m/s^2 as floats. Will
# return values in g if constructor was provided `accel_sf=SF_M_S2`
# parameter.
so = self._accel_so
sf = self._accel_sf

Expand All @@ -143,9 +139,7 @@ def acceleration(self):

@property
def gyro(self):
"""
X, Y, Z radians per second as floats.
"""
# X, Y, Z radians per second as floats.
so = self._gyro_so
sf = self._gyro_sf
ox, oy, oz = self._gyro_offset
Expand All @@ -161,15 +155,13 @@ def gyro(self):

@property
def temperature(self):
"""
Die temperature in celcius as a float.
"""
# Die temperature in celcius as a float.
temp = self._register_short(_TEMP_OUT_H)
return ((temp - _TEMP_OFFSET) / _TEMP_SO) + _TEMP_OFFSET

@property
def whoami(self):
""" Value of the whoami register. """
# Value of the whoami register.
return self._register_char(_WHO_AM_I)

def calibrate(self, count=256, delay=0):
Expand Down
Loading

0 comments on commit 10ece1b

Please sign in to comment.