Skip to content

Commit

Permalink
removr redundancy
Browse files Browse the repository at this point in the history
  • Loading branch information
Lovmong committed Jan 30, 2023
1 parent b77b60c commit dd24143
Showing 1 changed file with 24 additions and 22 deletions.
46 changes: 24 additions & 22 deletions libs/ws.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,8 @@
import time
import json


from machine import Pin
led = Pin(25, Pin.OUT)
onboard_led_ws = Pin(25, Pin.OUT)

"custom Exception"
class TimeoutError(Exception):
Expand Down Expand Up @@ -36,21 +35,26 @@ def __init__(self, name=None, ssid=None, password='', mode=None, port=8765):

self.send_dict["Name"] = self.name
print('reset ESP8266 module ...')
self.set("RESET", timeout=self.WS_TIMEOUT)

while True:
try:
self.set("RESET", timeout=1500 )
break
except TimeoutError:
pass
except UnicodeError:
pass
except Exception as e:
print(e)

def read(self, block=False):
buf = ""
# led_stat = False
while True:
# led.value(not led_stat)
buf = self.uart.readline()
if buf == None:
if block:
# time.sleep_ms(10)
time.sleep_ms(1)
continue
else:
# led.off()
return None
if buf[0] == 0xff:
buf = buf[1:]
Expand All @@ -60,7 +64,6 @@ def read(self, block=False):
buf = buf.replace("[DEBUG]", "[ESP8266]")
print(buf)
else:
# led.off()
return buf

def write(self, value):
Expand All @@ -79,11 +82,20 @@ def _command(self, mode, command, value=None):
command = "%s+%s" % (mode, command)
self.write(command)


def set(self, command, value=None, timeout=None):
self._command("SET", command, value)
t_s = time.ticks_ms()
flag = 0
while True:
if flag == 0:
onboard_led_ws.on()
flag = 1
time.sleep(0.1)
else:
onboard_led_ws.off()
flag = 0
time.sleep(0.1)

if timeout != None:
if(time.ticks_ms() - t_s > timeout):
raise TimeoutError('Set timeout %s ms'%timeout)
Expand Down Expand Up @@ -131,21 +143,12 @@ def start(self):
print("Connect Wifi error. Try another Wifi or AP mode.")
return False


def on_receive(self, data):
pass

def loop(self):
# print("waiting for uart data...")

st = time.ticks_ms()
receive = self.read()
# print('ws_rx_ut: ', time.ticks_ms()-st)

# print("Received.")
# print("ws loop, receive: %s" % receive)

# st = time.ticks_ms()
if receive == None:
self.send_data()
return
Expand All @@ -156,13 +159,12 @@ def loop(self):
print("Disconnected from %s" % receive.split(" ")[1])
else:
try:
# print("on revceive: %s" % receive)
data = json.loads(receive)
if isinstance(data, str):
data = json.loads(data)
self.on_receive(data)
self.send_data()
except ValueError as e:
print("\033[0;31m[%s\033[0m"%e)
self.send_data()
# print('ws_rh_ut: ', time.ticks_ms()-st)


0 comments on commit dd24143

Please sign in to comment.