<reponame>mzakharo/micropython
import utime as time
import ujson as json
from machine import WDT
from umqtt.robust import MQTTClient
from feathers2 import dotstar_color_wheel
import dotstar
from hcsr04 import HCSR04
from machine import Pin
from machine import I2C
#import VL53L0X
import adafruit_vl53l0x


# enable the WDT with a timeout of 5s (1s is the minimum)
wdt = WDT(timeout=20000)

def do_connect():
    import network
    wlan = network.WLAN(network.STA_IF)
    wlan.active(True)
    if not wlan.isconnected():
        print('connecting to network...')
        wlan.connect('wireless', 'W@terl004ever')
        while not wlan.isconnected():
            pass
    print('network config:', wlan.ifconfig())
do_connect()

client = MQTTClient(client_id = 'sonar', server='nas.local')
print('MQTT connect', client.connect())

RED= 0x100000
BLUE= 0x10
GREEN = 0x1000
colors = [RED, BLUE, GREEN]
dot = dotstar.DotStar(1,1,1)

sensor = HCSR04(trigger_pin=17, echo_pin=18)

'''
while True:
    print('distance', sensor.distance_cm())
    time.sleep(0.1)
    wdt.feed()
'''

i2c = I2C(0, scl=Pin(9), sda=Pin(8), freq=400000)

vl53 = adafruit_vl53l0x.VL53L0X(i2c)
vl53.measurement_timing_budget = 200000

# Main loop will read the range and print it every second.
#while True:
#    print("Range: {0}mm".format(vl53.range))
#    time.sleep(0.1)


# Create a VL53L0X object
#tof = VL53L0X.VL53L0X(i2c)
#tof.set_Vcsel_pulse_period(tof.vcsel_period_type[0], 18)
#tof.set_Vcsel_pulse_period(tof.vcsel_period_type[1], 14)
#tof.set_measurement_timing_budget(200000)
#tof.start()

#while True:
#    print(time.ticks_ms(), tof.read())
#    time.sleep(0.1)
#tof.stop()



#calibration
MAX_DIST = 50
MIN_DIST = 10


#MIN_LED-MAX_LED: from purple -> blue -> light blue, green -> yellow -> orange -> red
MIN_LED = 80
MAX_LED = 230

stride = 60
ldistance = []
tdistance = []
cnt = 0
last = time.ticks_ms()

brightness = True
with vl53.continuous_mode():
    while True:
        tic = time.ticks_ms()

        dists = []
        tofs = []
        for i in range(5):
            distance = -1.0

            #ignore errors in measurements
            while distance < 0:

                #wait 100ms between measurements
                diff = 0
                while diff < 200:
                    diff = time.ticks_diff(time.ticks_ms(), last)
                last = time.ticks_ms() 

                #measure
                distance = sensor.distance_cm()
                
            #distance_tof = tof.read() / 10.0
            distance_tof = vl53.range / 10.0
            tofs.append(distance_tof)

            #client.publish("sonar/status", json.dumps(dict(distance_raw=distance)))
            dists.append(distance)

        distance = sorted(dists)[3]
        distance_tof = sorted(tofs)[3]

        #convert distance to LED
        #Salt box is about 85cm in depth
        ratio = max(0, min(1, (distance - MIN_DIST) / (MAX_DIST - MIN_DIST)))
        led = int(MIN_LED + ratio * (MAX_LED-MIN_LED))

        color = dotstar_color_wheel(led)
        color = list(color)
        color.append(brightness)
        dot[0] = tuple(color)

        #blink LED on limit reached
        if distance >= MAX_DIST:
            brightness = not(brightness)
        else:
            brightness = True


        status = dict(distance=distance, distance_tof=distance_tof, led=led, ratio=int(ratio * 100))
        print('status', status)

        ldistance.append(distance)
        tdistance.append(distance_tof)

        cnt +=1
        if cnt == stride:
            cnt = 0
            distance = sum(ldistance) / len(ldistance)
            distance_tof = sum(tdistance) / len(tdistance)
            ldistance.clear()
            tdistance.clear()
            status = dict(distance=distance, distance_tof=distance_tof)
            print('pub_status', status)
            client.publish("sonar/status", json.dumps(status))

        wdt.feed()

        toc = time.ticks_diff(time.ticks_ms(), tic)
        dorm = 1000 - toc
        if dorm > 0:
            time.sleep_ms(dorm)
        else:
            print('WARNING: overrun by ', dorm, 'milisec')


import utime as time
import ujson as json
from machine import WDT
from umqtt.robust import MQTTClient
from feathers2 import dotstar_color_wheel
import dotstar
from hcsr04 import HCSR04
from machine import Pin
from machine import I2C
#import VL53L0X
import adafruit_vl53l0x


# enable the WDT with a timeout of 5s (1s is the minimum)
wdt = WDT(timeout=20000)

def do_connect():
    import network
    wlan = network.WLAN(network.STA_IF)
    wlan.active(True)
    if not wlan.isconnected():
        print('connecting to network...')
        wlan.connect('wireless', 'W@terl004ever')
        while not wlan.isconnected():
            pass
    print('network config:', wlan.ifconfig())
do_connect()

client = MQTTClient(client_id = 'sonar', server='nas.local')
print('MQTT connect', client.connect())

RED= 0x100000
BLUE= 0x10
GREEN = 0x1000
colors = [RED, BLUE, GREEN]
dot = dotstar.DotStar(1,1,1)

sensor = HCSR04(trigger_pin=17, echo_pin=18)

'''
while True:
    print('distance', sensor.distance_cm())
    time.sleep(0.1)
    wdt.feed()
'''

i2c = I2C(0, scl=Pin(9), sda=Pin(8), freq=400000)

vl53 = adafruit_vl53l0x.VL53L0X(i2c)
vl53.measurement_timing_budget = 200000

# Main loop will read the range and print it every second.
#while True:
#    print("Range: {0}mm".format(vl53.range))
#    time.sleep(0.1)


# Create a VL53L0X object
#tof = VL53L0X.VL53L0X(i2c)
#tof.set_Vcsel_pulse_period(tof.vcsel_period_type[0], 18)
#tof.set_Vcsel_pulse_period(tof.vcsel_period_type[1], 14)
#tof.set_measurement_timing_budget(200000)
#tof.start()

#while True:
#    print(time.ticks_ms(), tof.read())
#    time.sleep(0.1)
#tof.stop()



#calibration
MAX_DIST = 50
MIN_DIST = 10


#MIN_LED-MAX_LED: from purple -> blue -> light blue, green -> yellow -> orange -> red
MIN_LED = 80
MAX_LED = 230

stride = 60
ldistance = []
tdistance = []
cnt = 0
last = time.ticks_ms()

brightness = True
with vl53.continuous_mode():
    while True:
        tic = time.ticks_ms()

        dists = []
        tofs = []
        for i in range(5):
            distance = -1.0

            #ignore errors in measurements
            while distance < 0:

                #wait 100ms between measurements
                diff = 0
                while diff < 200:
                    diff = time.ticks_diff(time.ticks_ms(), last)
                last = time.ticks_ms() 

                #measure
                distance = sensor.distance_cm()
                
            #distance_tof = tof.read() / 10.0
            distance_tof = vl53.range / 10.0
            tofs.append(distance_tof)

            #client.publish("sonar/status", json.dumps(dict(distance_raw=distance)))
            dists.append(distance)

        distance = sorted(dists)[3]
        distance_tof = sorted(tofs)[3]

        #convert distance to LED
        #Salt box is about 85cm in depth
        ratio = max(0, min(1, (distance - MIN_DIST) / (MAX_DIST - MIN_DIST)))
        led = int(MIN_LED + ratio * (MAX_LED-MIN_LED))

        color = dotstar_color_wheel(led)
        color = list(color)
        color.append(brightness)
        dot[0] = tuple(color)

        #blink LED on limit reached
        if distance >= MAX_DIST:
            brightness = not(brightness)
        else:
            brightness = True


        status = dict(distance=distance, distance_tof=distance_tof, led=led, ratio=int(ratio * 100))
        print('status', status)

        ldistance.append(distance)
        tdistance.append(distance_tof)

        cnt +=1
        if cnt == stride:
            cnt = 0
            distance = sum(ldistance) / len(ldistance)
            distance_tof = sum(tdistance) / len(tdistance)
            ldistance.clear()
            tdistance.clear()
            status = dict(distance=distance, distance_tof=distance_tof)
            print('pub_status', status)
            client.publish("sonar/status", json.dumps(status))

        wdt.feed()

        toc = time.ticks_diff(time.ticks_ms(), tic)
        dorm = 1000 - toc
        if dorm > 0:
            time.sleep_ms(dorm)
        else:
            print('WARNING: overrun by ', dorm, 'milisec')
#import VL53L0X # enable the WDT with a timeout of 5s (1s is the minimum) while True:     print('distance', sensor.distance_cm())     time.sleep(0.1)     wdt.feed() # Main loop will read the range and print it every second. #while True: #    print("Range: {0}mm".format(vl53.range)) #    time.sleep(0.1) # Create a VL53L0X object #tof = VL53L0X.VL53L0X(i2c) #tof.set_Vcsel_pulse_period(tof.vcsel_period_type[0], 18) #tof.set_Vcsel_pulse_period(tof.vcsel_period_type[1], 14) #tof.set_measurement_timing_budget(200000) #tof.start() #while True: #    print(time.ticks_ms(), tof.read()) #    time.sleep(0.1) #tof.stop() #calibration #MIN_LED-MAX_LED: from purple -> blue -> light blue, green -> yellow -> orange -> red #ignore errors in measurements #wait 100ms between measurements #measure #distance_tof = tof.read() / 10.0 #client.publish("sonar/status", json.dumps(dict(distance_raw=distance))) #convert distance to LED #Salt box is about 85cm in depth #blink LED on limit reached