# A simple example of sending data to another device
# Run the program, and type in the command value you want sent to the other device

from machine import UART
import time
from umqtt.simple import MQTTClient

uart = UART(1, 9600, tx=17,
            rx=16)  # init with given baudrate that's that same as receiver
uart.init(9600, bits=8, parity=None, stop=1)  # init with given parameters


def sub_cb(topic, msg):
    # print(topic,msg)
    try:
        value = float(str(msg, 'utf-8'))  # convert subscribed value to a float
    except:
        value = msg.decode("utf-8")
    print("subscribed value = {}".format(value))
    uart.write(str(value) + "\n")  # \n need for the reciver using readline()


#
# configuration from io.adafruit.com: My Key
#
ADAFRUIT_IO_USERNAME = "******"  # can be found at "My Account" at adafruit.com
ADAFRUIT_IO_KEY = "enter your Adafruit IO Key here"  # can be found by clicking on "MY KEY" when viewing your account on io.adafruit.com

# only one program with the same MqttClient Name can access the Adarfuit service at a time
myMqttClient = "your_unique_id"  # replace with your own client name unique to you and this code instance
adafruitFeed = ADAFRUIT_IO_USERNAME + "/feeds/test"  # replace "test" with your feed name
# Manuel Lameira
# DTH 22 readings using MicroPython

# DTH22 --> ESP32
# GND   --> GND
# VCC   --> 5v or 3.3v
# DAT   --> D14

from machine import Pin, UART
from time import sleep

uart = UART(1, 9600)
uart.init(9600, bits=8, parity=None, stop=1,tx=17, rx=16,txbuf=512)

bin_arr = bytearray(b'') # Payload for test

for i in range(1,256): 
    bin_arr.append(i)

while True:
    
    uart.write(bin_arr)
#    time.sleep_us( ctl_up_us ) # !!! Problematic place
#    ctrlPin(0)    
    sleep(3)
    
#
#    ch = b""
#    print(ch)
#    while ch != b"quit":
#        if uart.any():
def init_UART(id, baud):
    uart = UART(id, baud)
    uart.init(115200, bits=8)
    return uart
Exemple #4
0
class Robot:
    def __init__(self, bus = 0, baud = 57600, dd = 5):
         
        self._uart = UART(bus, 19200)
        self._uart.init(19200, bits=8, parity=None, stop=1,  timeout=500, timeout_char=2)
      
        self._dd = machine.Pin(dd, machine.Pin.OUT)
        
        #wake roomba up
        self.wake_up()

        #pulse device detect three times to set baud 19200
        for i in range(3):
            self._dd.value(0)
            time.sleep(.25)
            self._dd.value(1)
            time.sleep(.25)

        #send start command 128
        self.send_uart(128)
        time.sleep(.1)

        #send control command 130
        self.send_uart(130)
        time.sleep(.1)

        #set full control 132
        self.send_uart(132)
        time.sleep(.1)

        #change baud to match uart0 115200
        #self.send_uart(129)
        #self.send_uart(11)
        #time.sleep(.1)

        #send control command 130
        #self.send_uart(130)
        #time.sleep(.1)

        #set full control 132
        #self.send_uart(132)
        #time.sleep(.1)

        #reconnect to uart with higher baudrate
        #self._uart.init(115200, bits=8, parity=None, stop=1)
        

    def vacuum(self, onoff):
        self.send_uart(138)
        self.send_uart(onoff)

    def turn_off(self):
        self.wake_up()
        self.send_uart(133)

    def wake_up(self):
        self._dd.value(0)
        time.sleep(.1)
        self._dd.value(1)
        time.sleep(2)

    def dock(self):
        #first set to spot mode
        self.send_uart(134)
        time.sleep(.1)

        #send dock command
        self.send_uart(143)
        time.sleep(.1)

       

    def send_uart(self, command):
        #uos.dupterm(self._uart, 1) #takeover uart from repl
        self._buf = command
        self._uart.write(bytearray([self._buf]))
        #uos.dupterm(None, 1) #give uart back to repl

    def recv_uart(self, num):
        #uos.dupterm(self._uart, 1) #takeover uart from repl
        while not self._uart.any():   
            pass
        data = self._uart.read(num)
        #uos.dupterm(None, 1) #give uart back to repl
        return data

    def get_sensors(self):
        #uos.dupterm(self._uart, 1) #takeover uart from repl
        self.send_uart(142)
        self.send_uart(2)
        #print(self._uart.read())
        data = self.recv_uart(26)
        #uos.dupterm(None, 1) #give uart back to repl
        for x in data:
            print(hex(x))

    def drive(self, velocity, radius):
        #first send drive command
        self.send_uart(137)
        time.sleep(.1)
        #next send velocity
        high = (velocity >> 8) & 0xff
        low = velocity & 0xff
        self.send_uart(high) #high byte first
        self.send_uart(low) #low byte

        #finally send radius
        high = (radius >> 8) & 0xff
        low = radius & 0xff
        self.send_uart(high) #high byte first
        self.send_uart(low) #low byte
    
    def stop(self):
        self.drive(0, 0)

    def forward(self, distance):
        #we want distance to be in inches more or less
        #at 102mm/s we go 1 inch in appx .25 seconds
        time_to_wait = distance / 4 #4 inches per second
        self.drive(102, 32768)
        time.sleep(time_to_wait)
        self.stop()

    def right(self, degree):
        #at 102mm/s we go appx 45 degrees per second
        time_to_wait = degree / 45
        self.drive(102, -1)
        time.sleep(time_to_wait)
        self.stop()

    def left(self, degree):
        #at 102mm/s we go appx 45 degrees per second
        time_to_wait = degree / 45
        self.drive(102, 1)
        time.sleep(time_to_wait)
        self.stop()

    def backward(self, distance):
        #we want distance to be in inches more or less
        #at 102mm/s we go 1 inch in appx .25 seconds
        time_to_wait = distance / 4 #4 inches per second
        self.drive(-102, 32768)
        time.sleep(time_to_wait)
        self.stop()

    def sound(self, note, duration):
        #note is the midi note id.
        #duration is in seconds
        self.send_uart(140) #create song
        self.send_uart(1) #song number
        self.send_uart(1) #song length
        self.send_uart(note) #note to play
        self.send_uart(round(duration * 64))
        time.sleep(.1)
        self.send_uart(141)
        self.send_uart(1) #play song 1
        time.sleep(duration) #need to wait to give roomba time to play note
        
#https://canvas.kdg.be/courses/23181/assignments/70984
from machine import UART

uart = UART(1)
uart.init(baudrate=9600, bits=8, parity=None, stop=1, timeout_chars=190)

while True:
    header_bytes = uart.read(1)
    data_header = int(uart.read(1)[0])
    data_high = int(uart.read(2)[0])
    data_low = int(uart.read(3)[0])
    distance = data_high * 256 + data_low
    if int(distance / 10) < 1000:
        print("Distance", int(distance / 10), "centimeter")
Exemple #6
0
from microWebSrv import MicroWebSrv
from machine import UART, RTC, Timer
import machine
import json
import ntptime
import esp32

try:
    uart = UART(1, 9600)
    uart.init(9600, bits=8, parity=None, stop=1, rx=13, tx=12, timeout=1000)
except:
    print("Exception Uart")
try:
    rtc = RTC()
    ntptime.settime()
except:
    print("Exception rtp")

websocketList = []
timer = Timer(0)
timer.init(freq=5, callback=lambda t: timerEvent())
_cmd = 0
_minmax = ""
_hold = ""
_rel = ""
_rangecount = 0


def timerEvent():
    #print("Timer Event")
    global _cmd
from main import hpfuncs
from machine import UART
global uart
uart = UART(1, 9600)
uart.init(9600,bits = 8,parity = 0,stop = 1,rx = 32,tx = 33,timeout = 10, timeout_char=50)
import uasyncio as asyncio
from main.mqtt_as import MQTTClient
from config import config
import time
from time import sleep
import machine
power_state = 'OFF'




#topic_prefix = "varmepumpe"
#mqtt_server = '192.168.2.30'
#client_id ='hpesp32-1'

topic_sub_setp =  b"" + config['maintopic'] + "/setpoint/set"
topic_sub_state =  b"" + config['maintopic'] + "/state/set"
topic_sub_fanmode =  b"" + config['maintopic'] + "/fanmode/set"
topic_sub_swingmode =  b"" + config['maintopic'] + "/swingmode/set"
topic_sub_mode =   b"" + config['maintopic'] + "/mode/set"
topic_sub_doinit =  b"" + config['maintopic'] + "/doinit"
topic_sub_restart =  b"" + config['maintopic'] + "/restart"
topic_sub_watchdog =  b"" + config['maintopic'] + "/watchdog"
topics = [topic_sub_setp, topic_sub_state, topic_sub_doinit, topic_sub_fanmode, topic_sub_mode, topic_sub_swingmode, topic_sub_restart, topic_sub_watchdog]

def int_to_signed(intval):
# ---------------
# GND --> GND
# VCC --> VCC
# AUX -->
# TX  --> RX (UART 2) 17
# RX  --> TX (UART 2) 16
# M1  -->
# M0  -->

from machine import UART, Pin
from time import sleep

buf = "hi"

uart = UART(2, 9600)
uart.init(9600, bits=8, parity=None, stop=1)

while True == True:
    val = uart.write(buf)
    print(val)
    sleep(1)

# from machine import I2C, Pin
# import utime
# from machine import UART

# uart = UART(0, 9600)
# uart.init(9600)

# while True==True:
#   val = uart.read()
Exemple #9
0
lora.add_channel(1, frequency=config.LORA_FREQUENCY, dr_min=0, dr_max=5)
lora.add_channel(2, frequency=config.LORA_FREQUENCY, dr_min=0, dr_max=5)
# join a network using ABP (Activation By Personalization)
lora.join(activation=LoRa.ABP, auth=(dev_addr, nwk_swkey, app_swkey))
# create a LoRa socket
s = socket.socket(socket.AF_LORA, socket.SOCK_RAW)
# set the LoRaWAN data rate
s.setsockopt(socket.SOL_LORA, socket.SO_DR, config.LORA_NODE_DR)
# make the socket non-blocking
s.setblocking(False)

# Create a GPS module instance.
#uart = UART(1, baudrate=9600, timeout_chars=3000, pins=('P8','P2'))
#uart = UART(1, baudrate=9600)
uart = UART(1, 9600, pins=('P22', 'P21'))
uart.init(baudrate=9600, bits=8, parity=None, stop=1, pins=('P22', 'P21'))
# Create a GPS module instance.
gps = adafruit_gps.GPS(uart)
print(gps)
# Turn on the basic GGA and RMC info (what you typically want)
gps.send_command('PMTK314,0,1,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0')
# Set update rate to once a second (1hz) which is what you typically want.
gps.send_command('PMTK220,1000')

last_print = time.ticks_ms()

while True:
    # Make sure to call gps.update() every loop iteration and at least twice
    # as fast as data comes from the GPS unit (usually every second).
    # This returns a bool that's true if it parsed new data (you can ignore it
    # though if you don't care and instead look at the has_fix property).
Exemple #10
0
class Music:
    def __init__(self, port):
        pin = getPin(port)
        if (pin[0] == None or pin[1] == None):
            from machine import reset
            reset()
        self.bus = UART(1, 9600)
        self.bus.init(baudrate=9600,
                      bits=8,
                      parity=None,
                      stop=1,
                      rx=pin[0],
                      tx=pin[1])

    def sendStack(self, cmd, param1, param2):
        while self.bus.any():
            self.bus.read()

        buff = bytearray([0x7E, 0xFF, 0x06, cmd, 0x01, param1, param2, 0xEF])
        self.bus.write(buff)
        nowTime = ticks_ms()
        while not self.bus.any():
            if ticks_diff(ticks_ms(), nowTime) > 5000:
                return

    #=====================================================
    def nextSong(self):
        self.sendStack(0x01, 0x00, 0x00)

    def previousSong(self):
        self.sendStack(0x02, 0x00, 0x00)

    def playSong(self, fileNumber):
        self.sendStack(0x03, fileNumber // 256, fileNumber % 256)

    def volumeUp(self):
        self.sendStack(0x04, 0x00, 0x00)

    def volumeDown(self):
        self.sendStack(0x05, 0x00, 0x00)

    def volume(self, volume):
        self.sendStack(0x06, 0x00, volume)

    def setEqualizer(self, eq):
        self.sendStack(0x07, 0x00, eq)

    def playLoop(self, fileNumber):
        self.sendStack(0x08, fileNumber // 256, fileNumber % 256)

    def outputDevice(self, device):
        self.sendStack(0x09, 0x00, device)
        delay(200)

    def sleep(self):
        self.sendStack(0x0A, 0x00, 0x00)

    def reset(self):
        self.sendStack(0x0C, 0x00, 0x00)
        delay(2000)

    def start(self):
        self.sendStack(0x0D, 0x00, 0x00)

    def pause(self):
        self.sendStack(0x0E, 0x00, 0x00)

    def playFolder(self, folder, song):
        self.sendStack(0x0F, folder, song)

    def outputSetting(self, enable, gain):
        self.sendStack(0x10, enable, gain)

    def enableLoopAll(self):
        self.sendStack(0x11, 0x00, 0x01)

    def disableLoopAll(self):
        self.sendStack(0x11, 0x00, 0x00)

    def playMP3Folder(self, file):
        self.sendStack(0x12, file // 256, file % 256)

    def advertise(self, file):
        self.sendStack(0x13, file // 256, file % 256)

    def stopAdvertise(self):
        self.sendStack(0x15)
        self.sendStack(0x16, 0x00, 0x00)

    def stop(self):
        self.sendStack(0x16, 0x00, 0x00)

    def loopFolder(self, folderNumber):
        self.sendStack(0x17, folderNumber // 256, folderNumber % 256)

    def randomAll(self):
        self.sendStack(0x18, 0x00, 0x00)

    def enableLoop(self):
        self.sendStack(0x19, 0x00, 0x00)

    def disableLoop(self):
        self.sendStack(0x19, 0x01, 0x00)

    def enableDAC(self):
        self.sendStack(0x1A, 0x00, 0x00)

    def disableDAC(self):
        self.sendStack(0x1A, 0x01, 0x00)

    def readState(self):
        return self._readRegister(0x42)

    def readVolume(self):
        return self._readRegister(0x43)

    def readEQ(self):
        return self._readRegister(0x44)

    def readFileCounts(self):
        return self._readRegister(0x48)

    def readCurrentFileNumber(self):
        return self._readRegister(0x4C)

    def readFileCountsInFolder(self, folder):
        return self._readRegister(0x4E, folder)

    def readFolderCounts(self):
        return self._readRegister(0x4F)

    def _readRegister(self, cmd, param=None):
        nowTime = ticks_ms()
        while self.bus.any():
            self.bus.read()

        if param == None:
            self.sendStack(cmd, 0x00, 0x00)
        else:
            self.sendStack(cmd, param // 256, param % 256)
        while not self.bus.any():
            if ticks_diff(ticks_ms(), nowTime) > 1000:
                return None
        buffer = self.bus.read(10)
        print(buffer)
        return buffer[5] * 256 + buffer[6]
class DigoleDisplay:
    def __init__(self, serial=1, baud=9600, width=240, height=320):
        self.width = width
        self.height = height

        #configure serial
        self.uart = UART(serial, 9600)
        self.uart.init(9600, bits=8, parity=None, stop=1)
        sleep_ms(100)
        if baud != 9600:
            self.uart.write("SB" + str(baud))
            sleep_ms(100)
            self.uart = UART(serial, baud)
            self.uart.init(baud, bits=8, parity=None, stop=1)
            sleep_ms(100)
            self.uart.write("CL")
            sleep_ms(100)
        self.uart.write("CL")
        sleep_ms(100)

    def write2B(self, v):
        if v < 255:
            self.uart.write(hex(v))
        else:
            self.uart.write(hex(255))
            self.uart.write(hex(v - 255))

    def brightness(self, i):
        v = str(i)
        if len(v) < 2:
            v = "0" + v
        self.uart.write("BL")
        self.uart.write(unhexlify(''.join(v)))

    def backLightOff(self):
        self.brightness(0)

    def disableCursor(self):
        self.uart.write("CS0")

    def enableCursor(self):
        self.uart.write("CS1")

    def clear(self):
        self.uart.write("CL")

    def displayConfig(self, v):
        self.uart.write("DC", v)

    def rotate0(self):
        self.uart.write("SD0")

    def rotate90(self):
        self.uart.write("SD1")

    def rotate180(self):
        self.uart.write("SD2")

    def rotate270(self):
        self.uart.write("SD3")

    def print(self, s):
        self.uart.write("TT")
        self.uart.write(s)
        self.uart.write("\x00")

    def println(self, s):
        self.uart.write("TT")
        self.uart.write(s)
        self.uart.write("\x00")
        self.uart.write("TRT")

    def drawLine(self, x, y, x1, y1):
        self.uart.write("LN")
        self.write2B(x)
        self.write2B(y)
        self.write2B(x1)
        self.write2B(y1)
Exemple #12
0
class ArloRobot(object):

    # com packet sending
    def com(self, packet, ret=False):

        msg = ""
        for i in packet:
            msg = msg + i + " "
        msg = msg[:-1] + "\r"
        if not ret:
            self.uart.write(bytes(msg, "utf-8"))
        else:
            for i in msg:
                self.uart.write(bytes(i, "utf-8"))
                # sleep_ms(self.pace)

        resp = ""
        data = ""
        if ret:
            while str(data) != str(b"\r") and data is not None:
                data = self.uart.read(1)
                # print(data)
                # sleep_ms(self.pace)
                if str(data) != str(b"\r"):
                    try:
                        resp = resp + str(data)[2:][:-1]
                    except Exception as e:
                        print(e)
            return resp
        else:
            self.uart.read()

    # set up/set down
    # serialid is defined as the ID of the serial bus from the
    # microcontroller, however tx and rx can be defined
    def __init__(self,
                 serial_id=2,
                 baudrate=19200,
                 timeout=30,
                 pace=0,
                 **kwargs):
        self.baudrate = baudrate
        self.serial_id = serial_id
        self.pace = 0
        self.timeout = timeout

        if "tx" in kwargs and "rx" in kwargs:
            self.uart = UART(self.serial_id, 19200)
            self.uart.init(
                19200,
                tx=kwargs.get("tx"),
                rx=kwargs.get("rx"),
                bits=8,
                parity=None,
                stop=1,
                txbuf=0,
                timeout=self.timeout,
            )
            print("TX pin and RX Pin defined.")
        else:
            self.uart = UART(self.serial_id, 19200)
            self.uart.init(19200,
                           bits=8,
                           parity=None,
                           stop=1,
                           txbuf=0,
                           timeout=self.timeout)

        self.com(["TXPIN", "CH2"])
        sleep(0.5)
        self.com(["RXPIN", "CH1"])
        sleep(0.5)
        self.com(["DEC"])
        sleep(0.5)
        self.com(["BAUD", str(self.baudrate)])
        sleep(0.5)

        if "tx" in kwargs and "rx" in kwargs:
            self.uart = UART(self.serial_id, self.baudrate)
            self.uart.init(
                self.baudrate,
                tx=kwargs.get("tx"),
                rx=kwargs.get("rx"),
                bits=8,
                parity=None,
                stop=1,
                txbuf=0,
                timeout=self.timeout,
            )
        else:
            self.uart = UART(self.serial_id, self.baudrate)
            self.uart.init(
                self.baudrate,
                bits=8,
                parity=None,
                stop=1,
                txbuf=0,
                timeout=self.timeout,
            )

        self.com(["PACE", str(pace)])
        self.pace = pace
        sleep(0.5)

    # end serial connection
    def end(self):
        self.uart.deinit()

    # -------------------------- movements methods------------------------

    # Turn command
    # motor_movements corresponds to the amount of encode positions
    # top_speed to the positions per second
    def turn(self, motor_movement, top_speed, ret=False):
        self.com(["TURN", str(motor_movement), str(top_speed)], ret)

    # arc turns the motors so that the platform moves along the arc of a circle
    # of a given radius with a speed and an angle
    def arc(self, radius, top_speed, angle, ret=False):
        self.com(["ARC", str(radius), str(top_speed), str(angle)], ret)

    # left/right -> -32767 to 32767
    # speed -> 1 to 32767
    def move(self, left, right, speed, ret=False):
        self.com(["MOVE", str(left), str(right), str(speed)], ret)

    # left/right -> -32767 to 32767
    def go_speed(self, left, right, ret=False):
        self.com(["GOSPD", str(left), str(right)], ret)

    # left/right -> -127 to 127
    def go(self, left, right, ret=False):
        self.com(["GO", str(left), str(right)], ret)

    def travel(self, distance, top_speed, angle, ret=False):
        self.com(["TRVL", str(distance), str(top_speed), str(angle)], ret)

    # --------------------------- information methods -----------------------

    def read_counts(self, ret=True):
        counts = self.com(["DIST"], ret)
        try:
            counts = counts.split(" ")
        except Exception as e:
            print(e)
        return counts

    def read_left_counts(self, ret=True):
        return self.com(["DIST"], ret)[0]

    def read_right_counts(self, ret=True):
        return self.com(["DIST"], ret)[1]

    def read_speeds(self, ret=True):
        speeds = self.com(["SPD"], ret)
        try:
            speeds = speeds.split(" ")
        except Exception as e:
            print(e)
        return speeds

    def read_left_speed(self, ret=True):
        return self.com(["SPD"], ret)[0]

    def read_right_speed(self, ret=True):
        return self.com(["SPD"], ret)[1]

    def read_head_angle(self, ret=True):
        data = self.com(["HEAD"], ret)
        try:
            if len(data) == 2:
                return int((data[1]))
            else:
                return int(data[0])
        except:
            return data

    def read_firmware_ver(self, ret=True):
        return self.com(["VER"], ret)

    def read_hardware_ver(self, ret=True):
        return self.com(["HWVER"], ret)

    def clear_counts(self, ret=True):
        return self.com(["RST"], ret)

    # ---------------------------- communication modes -----------------------

    def write_pulse_mode(self, ret=False):
        return self.com(["PULSE"], ret)

    def set_lf_mode(self, status, ret=False):
        return self.com(["SETLF", str(status)], ret)

    def set_hex_com(self, ret=False):
        return self.com(["HEX"], ret)

    def set_dec_com(self, ret=False):
        return self.com(["DEC"], ret)

    def set_echo_mode(self, status, ret=False):
        return self.com(["ECHO", str(status)], ret)

    def set_verbose_mode(self, status, ret=False):
        return self.com(["VERB", str(status)], ret)

    def set_rx_pin(self, pin, ret=False):
        return self.com(["RXPIN", str(pin)], ret)

    def set_tx_pin(self, pin, ret=False):
        return self.com(["TXPIN", str(pin)], ret)

    def set_baud_rate(self, baud, ret=False):
        return self.com(["BAUD", str(baud)], ret)

    def set_pwm_scale(self, scale, ret=False):
        return self.com(["SCALE", str(scale)], ret)

    def set_pace(self, pace, ret=False):
        return self.com(["PACE", str(pace)], ret)

    def set_hold(self, hold, ret=False):
        return self.com(["HOLD", str(baud)], ret)

    # -------------------------- closed loop constants ----------------------

    def set_ki_limit(self, limit, ret=False):
        return self.com(["KIP", str(limit)], ret)

    def set_ki_decay(self, decay, ret=False):
        return self.com(["KIT", str(decay)], ret)

    def set_kimax(self, maxim, ret=False):
        return self.com(["KIMAX", str(maxim)], ret)

    def set_ki_constant(self, constant, ret=False):
        return self.com(["KI", str(constant)], ret)

    def set_kp_constant(self, constant, ret=False):
        return self.com(["KP", str(constant)], ret)

    def set_acc_rate(self, acc, ret=False):
        return self.com(["ACC", str(acc)], ret)

    def set_ramp_rate(self, rate, ret=False):
        return self.com(["RAMP", str(rate)], ret)

    def set_live_zone(self, limit, ret=False):
        return self.com(["LZ", str(limit)], ret)

    def set_dead_zone(self, limit, ret=False):
        return self.com(["DZ", str(limit)], ret)

    def set_ppr(self, ppr, ret=False):
        return self.com(["PPR", str(ppr)], ret)

    # -------- config ----------
    def restore_config(self, ret=False):
        return self.com(["RESTORE"], ret)

    def read_config(self, command, ret=True):
        return self.com([command], ret)
Exemple #13
0
from machine import RTC
from machine import Timer

blinky = Timer(0)
limitOpen = Pin(35, Pin.IN)            # Labeled SW1
limitClose = Pin(34, Pin.IN)           # Labeled SW2
buttonOpen = Pin(32, Pin.IN)           # Labeled B1
buttonClose = Pin(10, Pin.IN)          # Labeled B2
indicatorLight = Pin(5, Pin.OUT)       # Labeled L1

pins = [limitOpen, limitClose, buttonOpen, buttonClose]

debounceDelay = 150                    # in milliseconds

drive = UART(2,9600,tx=17,rx=16)
drive.init(9600, bits=8, parity=None, stop=1)  # 9600 baud, 8 data bits, 1 stop bit, no parity
time.sleep_ms(100)

closedPosition = '80800'                      # distance in steps to close / open doors
openPosition = '2100'                          # defined as a string so it can be sent over serial
spi = 3031                                     # steps per inch of the motor/sprocket/belt
limitDistance = 2100                           # number of steps from contact with limit switch to switch engaging. Use to back motor off once limit has been hit. (eg, after homing)

#CONSOLE_IP = '10.0.0.100'                  # Make this the same as the IP address of the lighting console
#console = Client(CONSOLE_IP, 8000)         # creates an OSC client that will send commands to the lighting console at CONSOLE_IP

actuations = 0
homed = False
#nic = network.LAN(mdc = Pin(23), mdio = Pin(18), power = Pin(17), phy_type = network.PHY_LAN8720, phy_addr=0)

'''
Exemple #14
0
def connect():
    global uart0
    uart0 = UART(0)
    uart0.init(baudrate=115200, bits=8, parity=None, stop=1)
    uos.dupterm(uart0)
Exemple #15
0
import pycom
from machine import UART, Pin, ADC
from LTR329ALS01 import LTR329ALS01
import ujson as json
import urequests as requests
import utime as time

pycom.heartbeat(
    False)  # Don't let the heartbeat LED interfere with the light sensor

#
# USB Serial initialization
#
uart = UART(0)  # init with given bus
uart.init(115200, bits=8, parity=None,
          stop=1)  # init with given parameters:  Baudrate=9600

#
# Light sensor initialization
#
print("Initializing Light sensor")
integration_time = LTR329ALS01.ALS_INT_50  # Integration time of the light sensor.
measurement_rate = LTR329ALS01.ALS_RATE_50  # A lower rate means higher sampling rate i.e. ALS_50 is quick, ALS_2000 is slow.
# MUST be equal or larger than integration time
gain = LTR329ALS01.ALS_GAIN_1X  # A higher gain means a more precise measures in the lower end i.e. 8X gives a range [0.125, 8K] lux

lightsensor = LTR329ALS01(integration=integration_time,
                          rate=measurement_rate,
                          gain=gain)

#
Exemple #16
0
from machine import UART, I2C, Pin, WDT
from binascii import hexlify
import ssd1306
from sml_extr import extract_sml
from simple_mqtt import MQTTClient
import utime
import ntptime
#############################################################
#board configuration
i2c = I2C(scl=Pin(4), sda=Pin(5))
oled = ssd1306.SSD1306_I2C(128, 64, i2c)
onbled = Pin(2, Pin.OUT)  # onboard led (blue)
uart = UART(2, 9600)
uart.init(9600, bits=8, parity=None, stop=1, timeout=100, timeout_char=100, rx=13, tx=15)  # init with given parameters

timezone = 0
sumtime = 0

# wifi
ssid = 'Cookie'
password = '******'

publish_int = 60  # Sekunden
buf = bytearray(500)

# mqtt settings
mqtt_server = "myServer"
mqtt_port = 8883  # using SSL/TLS (non-SSL = 1883)
mqtt_user = "******"
mqtt_pw = "PASSWORD"
mqtt_client_id = "myDevice"
Exemple #17
0
class uart_class(object):
    def __init__(self, port, baudrate=115200):
        self.port = PORT[port]
        self.uart = UART(self.port, baudrate)
        if (self.port == PORT["PORT1"]):
            self.timeout = 3
        else:
            self.timeout = 20

    @decorator
    def open(baudrate=115200):
        self.uart.init(baudrate)
        return self.uart

    @decorator
    def close():
        pass

    @decorator
    def write(self, data):
        self.uart.write(data)

    @decorator
    def read(self, len=MAX_RECEIVE_SIZE, timeout=0):
        _bytes = self.uart.read(len, timeout)
        return _bytes

    @decorator
    def recv_packet(self, respond_type):
        m_state = STATE_SYNC
        m_length = 0
        m_sync = 0
        m_checksum = 0
        while (True):
            buff = self.read(len=1, timeout=self.timeout)
            #print(buff)
            if buff:
                if m_state == STATE_SYNC:
                    m_sync = (buff[0] << 8) | m_sync
                    m_sync = m_sync & 0xFFFF
                    if (m_sync == PIXY_CHECKSUM_SYNC):
                        m_state = STATE_PACKET_TYPE
                    elif (m_sync == PIXY_NO_CHECKSUM_SYNC):
                        m_state = STATE_PACKET_TYPE
                    else:
                        m_sync = buff[0]
                elif m_state == STATE_PACKET_TYPE:
                    if (buff[0] == respond_type):
                        m_state = STATE_DATA_LEN
                    else:
                        m_state = STATE_SYNC
                elif m_state == STATE_DATA_LEN:
                    m_length = buff[0]
                    if m_sync == PIXY_CHECKSUM_SYNC:
                        m_state = STATE_DATA_CHECK_SUM_L
                    else:
                        m_state = STATE_DATA_BUFF
                elif m_state == STATE_DATA_CHECK_SUM_L:
                    m_checksum = buff[0]
                    m_state = STATE_DATA_CHECK_SUM_H
                elif m_state == STATE_DATA_CHECK_SUM_H:
                    m_checksum = (buff[0] << 8) | m_checksum
                    m_state = STATE_DATA_BUFF
                else:
                    pass

                if m_state == STATE_DATA_BUFF:
                    data = self.read(len=m_length, timeout=10)
                    if (data):
                        if (len(data) != m_length):
                            #print("recv_packet tm_length error!")
                            return None
                        if m_sync == PIXY_CHECKSUM_SYNC:
                            csCalc = sum(data) & 0xFFFF
                            if (m_checksum != csCalc):
                                #print("recv_packet checksum error!")
                                return None
                            return data
                        else:
                            return data
                    else:
                        #print("recv_packet read data timeout!")
                        return None
                else:
                    pass
            else:
                #print("recv_packet timeout!")
                return None

    @decorator
    def send_packet(self, m_type, m_len, data=[]):
        m_buf = bytearray()
        m_buf.append(PIXY_NO_CHECKSUM_SYNC & 0xff)
        m_buf.append(PIXY_NO_CHECKSUM_SYNC >> 8)
        m_buf.append(m_type)
        m_buf.append(m_len)
        for i in range(len(data)):
            m_buf.append(data[i])
        return self.write(m_buf)
Exemple #18
0
from machine import UART
import utime

FONA_BAUD = 4800

uart = UART(2, FONA_BAUD)  # for UART2 on esp32 dev board, RX:16, TX:17
uart.init(FONA_BAUD)

# clear the buffer
for i in range(3):
    uart.readline()

# check replies
for i in range(10):
    message = "AT"
    uart.write(message + '\r\n')  # \r and \n seem necessary
    print(">>\n" + message)
    utime.sleep(.1)
    response = uart.read().decode('ascii')
    print("<<")
    print(response.split())
    utime.sleep(.1)
Exemple #19
0
import select
import secrets

DEBUG = True

DEFAULT_MESHNAME = secrets.DEFAULT_MESHNAME
DEFAULT_MESHPWD = secrets.DEFAULT_MESHPWD
SSID = secrets.SSID
PASS = secrets.PASS

DEFAULT_DSTADDR = "FFFF"
DEFAULT_OPCODE = "D0"
DEFAULT_PARS = "010000"

m_uart = UART(2, tx=18, rx=4)  # init with given baudrate
m_uart.init(115200, bits=8, parity=None, stop=1, timeout=10)

poll = select.poll()
poll.register(m_uart, select.POLLIN)


def _send_command(cmd='AT'):
    if DEBUG: print("DEBUG: Sending %s to BLE Module" % cmd)
    m_uart.write(cmd + '\r\n')
    time.sleep(0.3)


def send_command(cmd):
    command = 'AT+' + cmd
    _send_command(command)
Exemple #20
0
class DeepSleep:

    WPUA_ADDR = const(0x09)
    OPTION_REG_ADDR = const(0x0E)
    IOCAP_ADDR = const(0x1A)
    IOCAN_ADDR = const(0x1B)

    WAKE_STATUS_ADDR = const(0x40)
    MIN_BAT_ADDR = const(0x41)
    SLEEP_TIME_ADDR = const(0x42)
    CTRL_0_ADDR = const(0x45)

    EXP_RTC_PERIOD = const(7000)

    def __init__(self):
        self.uart = UART(1, baudrate=10000, pins=(COMM_PIN, ), timeout_chars=5)
        self.clk_cal_factor = 1
        self.uart.read()
        # enable the weak pull-ups control
        self.clearbits(OPTION_REG_ADDR, 1 << 7)

    def _send(self, data):
        self.uart.write(bytes(data))

    def _start(self):
        self.uart.sendbreak(12)
        self._send([0x55])

    def _magic(self, address, and_val, or_val, xor_val, expected=None):
        self._start()
        self._send([address, and_val & 0xFF, or_val & 0xFF, xor_val & 0xFF])
        if expected is None:
            return self.uart.read()
        else:
            if expected > 0:
                return self.uart.read(expected)

    def _add_to_pin_mask(self, mask, pin):
        if pin == 'P10' or pin == 'G17':
            mask |= 0x01
        elif pin == 'P17' or pin == 'G31':
            mask |= 0x02
        elif pin == 'P18' or pin == 'G30':
            mask |= 0x08
        else:
            raise ValueError('Invalid Pin specified: {}'.format(pin))
        return mask

    def _create_pin_mask(self, pins):
        mask = 0
        if type(pins) is str:
            mask = self._add_to_pin_mask(mask, pins)
        else:
            for pin in pins:
                mask = self._add_to_pin_mask(mask, pin)
        return mask & PIN_MASK

    def poke(self, address, value):
        self._magic(address, 0, value, 0)

    def peek(self, address):
        try:
            return self._magic(address, 0xFF, 0, 0)[6]
        except:
            return self._magic(address, 0xFF, 0, 0)[6]

    def setbits(self, address, mask):
        self._magic(address, 0xFF, mask, 0)

    def clearbits(self, address, mask):
        self._magic(address, ~mask, 0, 0)

    def togglebits(self, address, mask):
        self._magic(address, 0xFF, 0, mask)

    def calibrate(self):
        """ The microcontroller will send the value of CTRL_0 after setting the bit
            and then will send the following pattern through the data line:

               val | 1 | 0 | 1*| 0 | 1*| 0 | 1
               ms  | 1 | 1 | 1 | 1 | 8 | 1 | -

            The idea is to measure the real life duration of periods marked with *
            and substract them. That will remove any errors common to both measurements
            The result is 7 ms as generated by the PIC LF clock.
            It can be used to scale any future sleep value. """

        # setbits, but limit the number of received bytes to avoid confusion with pattern
        self._magic(CTRL_0_ADDR, 0xFF, 1 << 2, 0, 0)
        self.uart.deinit()
        self._pulses = pycom.pulses_get(COMM_PIN, 150)
        self.uart.init(baudrate=10000, pins=(COMM_PIN, ), timeout_chars=5)
        idx = 0
        for i in range(len(self._pulses)):
            if self._pulses[i][1] > EXP_RTC_PERIOD:
                idx = i
                break
        try:
            self.clk_cal_factor = (self._pulses[idx][1] -
                                   self._pulses[(idx - 1)][1]) / EXP_RTC_PERIOD
        except:
            self.clk_cal_factor = 1
        if self.clk_cal_factor > 1.25 or self.clk_cal_factor < 0.75:
            self.clk_cal_factor = 1

    def enable_auto_poweroff(self):
        self.setbits(CTRL_0_ADDR, 1 << 1)

    def enable_pullups(self, pins):
        mask = self._create_pin_mask(pins)
        self.setbits(WPUA_ADDR, mask)

    def disable_pullups(self, pins):
        mask = self._create_pin_mask(pins)
        self.clearbits(WPUA_ADDR, mask)

    def enable_wake_on_raise(self, pins):
        mask = self._create_pin_mask(pins)
        self.setbits(IOCAP_ADDR, mask)

    def disable_wake_on_raise(self, pins):
        mask = self._create_pin_mask(pins)
        self.clearbits(IOCAP_ADDR, mask)

    def enable_wake_on_fall(self, pins):
        mask = self._create_pin_mask(pins)
        self.setbits(IOCAN_ADDR, mask)

    def disable_wake_on_fall(self, pins):
        mask = self._create_pin_mask(pins)
        self.clearbits(IOCAN_ADDR, mask)

    def get_wake_status(self):
        # bits as they are returned from PIC:
        #   0: PIN 0 value after awake
        #   1: PIN 1 value after awake
        #   2: PIN 2 value after awake
        #   3: PIN 3 value after awake
        #   4: TIMEOUT
        #   5: POWER ON

        wake_r = self.peek(WAKE_STATUS_ADDR)
        return {
            'wake': wake_r & (TIMER_WAKE | POWER_ON_WAKE),
            'P10': wake_r & 0x01,
            'P17': (wake_r & 0x02) >> 1,
            'P18': (wake_r & 0x08) >> 3
        }

    def set_min_voltage_limit(self, value):
        # voltage value passed in volts (e.g. 3.6) and round it to the nearest integer
        value = int(((256 * 2.048) + (value / 2)) / value)
        self.poke(MIN_BAT_ADDR, value)

    def go_to_sleep(self, seconds):
        gc.collect()
        while True:
            try:
                self.calibrate()
            except Exception:
                pass

            # the 1.024 factor is because the PIC LF operates at 31 KHz
            # WDT has a frequency divider to generate 1 ms
            # and then there is a binary prescaler, e.g., 1, 2, 4 ... 512, 1024 ms
            # hence the need for the constant

            # round to the nearest integer
            seconds = int((seconds / (1.024 * self.clk_cal_factor)) + 0.5)
            self.poke(SLEEP_TIME_ADDR, (seconds >> 16) & 0xFF)
            self.poke(SLEEP_TIME_ADDR + 1, (seconds >> 8) & 0xFF)
            self.poke(SLEEP_TIME_ADDR + 2, seconds & 0xFF)
            self.setbits(CTRL_0_ADDR, 1 << 0)

    def hw_reset(self):
        self.setbits(CTRL_0_ADDR, 1 << 4)
Exemple #21
0
from machine import Pin, UART
from umqtt.simple import MQTTClient
import time
import uos

uos.dupterm(None, 1)
uart = UART(0, 115200)
uart.init(baudrate=115200, bits=8, parity=None, stop=1, timeout=10, rx=Pin(3))
buff = 1024

c = MQTTClient('umqtt_client', '47.98.224.249')
c.connect()
read = b''
uart.write(bytearray('111'))
while True:
    if uart.any():
        read = uart.read(11)
        uart.write(read)
        c.publish(b'test', read)
class M5310_A():
    def send_cmd(self, cmd):
        self.uart.write(cmd + '\r\n')

    def cheak_ack(self, buf, ack):
        if ack in buf:
            return True
        else:
            return False

    def __init__(self):
        self.rst = Pin(18, Pin.OUT)
        self.uart = UART(2)
        self.uart.init(9600, bits=8, parity=None, stop=1)
        self.RecvMax = 128
        self.RecvBuf = bytearray()
        self.cmd = [
            'AT', 'AT+CIMI', 'AT+COPS=1,2,\"46000\"', 'AT+CSQ', 'AT+CEREG?',
            'AT+CGATT?', 'AT+NSOCR="DGRAM",17,0,1', 'AT+NSOCFG=0',
            'AT+NSOCFG=0,0,0'
        ]
        self.cmd_len = len(self.cmd)
        self.cmd_index = 0
        self.set_up()

    def set_up(self):
        self.rst.value(1)
        utime.sleep_ms(200)
        self.rst.value(0)
        self.send_cmd(self.cmd[self.cmd_index])
        send_time = utime.ticks_ms()
        while True:
            recvlen = self.uart.any()
            if recvlen > 0:
                buffer = self.uart.read(recvlen)
                for data in buffer:
                    self.RecvBuf.append(data)
                if self.cmd[self.cmd_index] == 'AT' or self.cmd[self.cmd_index] == 'AT+CIMI' \
                        or self.cmd[self.cmd_index] == 'AT+COPS=1,2,\"46000\"' or self.cmd[self.cmd_index] ==\
                        'AT+NSOCFG=0' or self.cmd[self.cmd_index] == 'AT+NSOCFG=0,0,0':
                    if self.cheak_ack(self.RecvBuf, b'\r\nOK\r\n'):
                        print('CHEAK_OK')
                        print(self.RecvBuf)
                        self.RecvBuf = bytearray()
                        self.cmd_index += 1
                        if self.cmd_index >= self.cmd_len:
                            break
                        else:
                            self.send_cmd(self.cmd[self.cmd_index])
                            send_time = utime.ticks_ms()
                elif self.cmd[self.cmd_index] == 'AT+CSQ':
                    if self.cheak_ack(self.RecvBuf, b'\r\n+CSQ:'):
                        print('CHEAK_OK')
                        print(self.RecvBuf)
                        strbuf = bytes(self.RecvBuf)
                        print(strbuf)
                        num = strbuf.find(b':')
                        csq = int(strbuf[num + 1:num + 3])
                        if csq > 12 and csq < 99:
                            self.RecvBuf = bytearray()
                            self.cmd_index += 1
                            if self.cmd_index >= self.cmd_len:
                                break
                            else:
                                self.send_cmd(self.cmd[self.cmd_index])
                                send_time = utime.ticks_ms()
                elif self.cmd[self.cmd_index] == 'AT+CGATT?':
                    if self.cheak_ack(self.RecvBuf, b'+CGATT:1'):
                        print('CHEAK_OK')
                        print(self.RecvBuf)
                        self.RecvBuf = bytearray()
                        self.cmd_index += 1
                        if self.cmd_index >= self.cmd_len:
                            break
                        else:
                            self.send_cmd(self.cmd[self.cmd_index])
                            send_time = utime.ticks_ms()
                elif self.cmd[self.cmd_index] == 'AT+CEREG?':
                    if self.cheak_ack(self.RecvBuf, b'+CEREG:0'):
                        print('CHEAK_OK')
                        print(self.RecvBuf)

                        strbuf = bytes(self.RecvBuf)
                        print(strbuf)
                        num = strbuf.find(b'G:')
                        reg = int(strbuf[num + 4:num + 5])
                        if reg == 1 or reg == 5:
                            self.RecvBuf = bytearray()
                            self.cmd_index += 1
                            if self.cmd_index >= self.cmd_len:
                                break
                            else:
                                self.send_cmd(self.cmd[self.cmd_index])
                                send_time = utime.ticks_ms()
                elif self.cmd[self.cmd_index] == 'AT+NSOCR="DGRAM",17,0,1':
                    if self.cheak_ack(self.RecvBuf, b'\r\nOK\r\n'):
                        print('CHEAK_OK')
                        print(self.RecvBuf)
                        strbuf = bytes(self.RecvBuf)
                        print(strbuf)
                        num = strbuf.find(b'\r\nOK\r\n')
                        reg = int(strbuf[num - 3]) - 48
                        print(reg)
                        if reg >= 0 and reg <= 6:
                            self.RecvBuf = bytearray()
                            self.cmd_index += 1
                            if self.cmd_index >= self.cmd_len:
                                break
                            else:
                                self.send_cmd(self.cmd[self.cmd_index])
                                send_time = utime.ticks_ms()
            if (len(self.RecvBuf) > self.RecvMax):
                self.RecvBuf = bytearray()
                print('OUT LINE')
                self.send_cmd(self.cmd[self.cmd_index])
                print('resend:', self.cmd[self.cmd_index])
                send_time = utime.ticks_ms()
            now_time = utime.ticks_ms()
            if send_time + 500 < now_time:
                self.RecvBuf = bytearray()
                self.send_cmd(self.cmd[self.cmd_index])
                print('resend:', self.cmd[self.cmd_index])
                send_time = utime.ticks_ms()

    def send_data(self, data):
        data = 'AT+NSOST=0,zwidas.top,8888,,\"%s\"' % data
        self.send_cmd(data)
def inituart(num):
    global uart
    uart = UART(num, 9600)
    uart.init(9600, bits=8, parity=None, stop=1)
Exemple #24
0
# Test of UART conection with ESP32 and Ebyte E32

# E32 --> ESP32
# ---------------
# GND --> GND
# VCC --> VCC
# AUX -->
# TX  --> RX (UART 2) 17
# RX  --> TX (UART 2) 16
# M1  -->
# M0  -->

from machine import UART, Pin

uTX = Pin(17)
uRX = Pin(16)

uart = UART(1, 9600)
uart.init(9600, bits=8, parity=None, stop=1, uTX, uRX)

# from machine import I2C, Pin
# import utime
# from machine import UART

# uart = UART(0, 9600)
# uart.init(9600)

# while True==True:
#   val = uart.read()
#   print(val)
#   utime.sleep(1)
from unm3driver import Nm3

# Wait for few seconds to turn on the 3.3V supply
utime.sleep(3.0)

# Switch ON 3.3V to TTL-RS232 converter
p33v_1 = Pin('EN_3V3', mode=Pin.OUT, pull=Pin.PULL_UP, value=1)

utime.sleep(2.0)

# Initialize UART
uart1 = UART(1, 9600)
uart1.init(9600,
           bits=8,
           parity=None,
           stop=1,
           timeout=50,
           flow=0,
           timeout_char=0,
           read_buf_len=64)

# Instantiate Nm3
nm3 = Nm3(uart1)

# Instantiate LEDs
led_R = LED(1)
led_G = LED(2)

led_R.off()
led_G.off()

#utime.sleep(6.0)
    .button2{background-color: #4286f4;}</style></head><body> <h1>ESP Web Server</h1>
    <p>Current Time: <strong>""" + gpio_state + """</strong></p><p><a href="/?music=on"><button class="button">Music</button></a></p>
    </body></html>"""
    return html


s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(('', 80))
s.listen(5)

# Updates from OpenMV send
curr_time = ''

# uart init
uart = UART(2, 115200)
uart.init(115200, bits=8, parity=None, stop=1)

while True:
    conn, addr = s.accept()
    time.sleep(0.1)
    # Update based on uart read
    read = uart.readline()
    if read == None:
        pass
    # At least do a type check for URL error
    else:
        curr_time = read.decode("ascii")
        curr_time = curr_time.rstrip()
    print('Got a connection from %s' % str(addr))
    request = conn.recv(1024)
    request = str(request)
Exemple #27
0
class SecureElement:
    def __init__(self):
        # these required changes to ss/uart.c
        self.ow = UART(4,
                       baudrate=230400,
                       bits=7,
                       parity=None,
                       stop=1,
                       timeout=1,
                       read_buf_len=(180 * 8))

        # correct pin settings, because we have external pullup
        self.pa0 = Pin('A0',
                       mode=Pin.ALT_OPEN_DRAIN,
                       pull=Pin.PULL_NONE,
                       af=Pin.AF8_UART4)

        # LSB first, 0x88 = Transmit
        self.x88 = self.serialize(bytes([IOFLAG_TX]))

        # selftest
        test = b'\xa5'
        chk = self.serialize(test)
        chk2 = self.deserialize(chk)
        assert chk2 == test, (chk2, test)

        test_crc16w()

        self.d_slot = [None] * 16
        self.data = None

        try:
            self.read()
        except:
            print("AE failed")
            self.data = None

    def reinit(self):
        # When bootloader accesses the UART, it clears interrupt enable bits
        # so reading doesn't work. Reinit UART to fix.
        self.ow.init(baudrate=230400,
                     bits=7,
                     parity=None,
                     stop=1,
                     timeout=1,
                     read_buf_len=(80 * 8))

    def deserialize(self, bb, offset=0):
        # deserialize bits received as bytes. maybe skip over N leading bytes
        rv = bytearray((len(bb) // 8) - offset)

        pos, o = (8 * offset), 0
        while 1:
            mask = 0x01
            for c in bb[pos:pos + 8]:
                if c == BIT1:
                    rv[o] |= mask
                mask <<= 1
            pos += 8
            o += 1
            if pos >= len(bb):
                break

        return rv

    def serialize(self, msg):
        # turn bits into 8x longer bits
        rv = bytearray(len(msg) * 8)

        for pos, c in enumerate(msg):
            mask = 0x01
            for i in range(8):
                rv[(pos * 8) + i] = BIT1 if (c & mask) else BIT0
                mask <<= 1

        return rv

    def go_idle(self):
        # XXX ?? idle then wakeup more useful, but no wakeups needed
        # This is useful to reset watchdog timer.
        ow = self.ow
        ow.write(b'\x00')  # WAKEUP token
        ow.read()  # thow out old garbage
        sleep_us(2500)  # tWHI: 2.5ms min
        ow.write(self.serialize(bytes([IOFLAG_IDLE])))
        #sleep_us(40)      # tTURNAROUND (80)

    def reset_watchdog(self):
        ow.write(self.serialize(bytes([IOFLAG_IDLE])))

    def reset_chip(self):
        self.go_sleep()

    def go_sleep(self):
        # This is useful to clear voltile state explicitly
        ow = self.ow
        ow.write(b'\x00')  # WAKEUP token
        ow.read()  # thow out old garbage
        sleep_us(2500)  # tWHI: 2.5ms min
        ow.write(self.serialize(bytes([IOFLAG_SLEEP])))
        #sleep_us(40)      # tTURNAROUND (80)

    def assume_data_blank(self):
        "data area is probably blank"
        self.d_slot = [(b'\xff' * slot_layout(sl)[1]) for sl in range(16)]

    def try_read_data(self, skip=[]):
        "try to read all slots; some will fail w/ private data"
        # XXX doesn't recover well from failed reads; avoid them
        for sl in range(16):
            if sl in skip:
                self.d_slot[sl] = None
                continue
            try:
                self.read_data_slot(sl)
            except RuntimeError:
                self.d_slot[sl] = None

    def send_recv(self,
                  opcode=None,
                  p1=0,
                  p2=0,
                  body=b'',
                  resp_len=1,
                  delay=None):
        #
        # Send a command block and read response. Sometimes a delay is needed.
        #
        # use a special setup packet to WRITE a command/value to device under test
        # see ../ae.h for struct aeCmdResponse_t

        assert len(body) <= 77
        assert 1 <= resp_len <= 65, resp_len
        assert opcode

        # organize packet:
        #  flag, len, op, p1, p2, (body), crc1, crc2
        pkt = ustruct.pack('BBBBH', IOFLAG_CMD, 1 + 1 + 1 + 2 + len(body) + 2,
                           opcode, p1, p2)
        pkt += body
        pkt += crc16w(pkt[1:])

        pkt = self.serialize(pkt)

        ow = self.ow
        ow.write(b'\x00')  # WAKEUP token
        ow.read()  # thow out old garbage
        sleep_us(2500)  # tWHI: 2.5ms min
        ow.write(pkt)
        sleep_us(40)  # tTURNAROUND (80)

        if delay is None:
            # delay is required, but complete table is annoying
            if opcode in (OP.DeriveKey, OP.ECDH, OP.PrivWrite, OP.Sign):
                delay = 60
            elif opcode in (OP.GenKey, ):
                delay = 120
            else:
                delay = 20

        # delay for chip to do it's maths
        sleep_ms(delay)

        while 1:
            # read back response
            ow.write(b'\x00')  # WAKEUP token
            while ow.any():
                ow.read(1)  # thow out old garbage
            sleep_us(2500)  # tWHI: 2.5ms min
            ow.write(self.x88)

            # expect back
            # - the TX token (echo)
            # - length byte
            # - 1+ body
            # - 2 bytes CRC
            #
            resp = ow.read(8 * (1 + 1 + resp_len + 2))

            if not resp:
                # chip wasn't ready yet: retry
                continue

            resp = self.deserialize(resp, 1)
            #print("resp: %r" % resp)

            if len(resp) < 4:
                # chip wasn't ready? Noise?
                raise WrongResponseLength(len(resp))

            if resp_len != resp[0] - 3:
                if (resp[0] == 4) and (crc16w(resp[:-2]) == resp[-2:]):
                    # probably an error response
                    raise ChipErrorResponse(hex(resp[1]))

                #print("wr len: %r" % resp)
                raise WrongResponseLength(len(resp))

            # check CRC, over all but last two bytes.
            expect = crc16w(resp[:-2])

            if expect != resp[-2:]:
                raise CRCError()

            return resp[1:-2]

    def ae_cmd(self, **kws):
        # return whatever bytes that come back
        return self.send_recv(**kws)

    def ae_cmd1(self, **kws):
        # returns the one byte
        kws.setdefault('resp_len', 1)
        return self.send_recv(**kws)[0]

    def read(self):
        "read entire CONFIG space: 4*32 bytes"
        rv = bytearray()
        for n in range(4):
            args = read_params(block=n, is_config=1)
            rv += self.ae_cmd(opcode=OP.Read, **args)

        self.data = rv

    def read_data_slot(self, slot_num, blkcount=None):
        "read a DATA slot, completely.. can be up to 3k of data"

        num_blocks, num_bytes = slot_layout(slot_num)

        d = b''
        for i in range(num_blocks):
            self.reset_watchdog()

            if blkcount is not None and i >= blkcount: break

            args = read_params(block=i,
                               slot=slot_num,
                               is_config=False,
                               is_data=True,
                               offset=0)
            d += self.ae_cmd(opcode=OP.Read, **args)

        d = d[0:num_bytes]
        #XXX waste of memory##self.d_slot[slot_num] = d

        return d

    def get_serial(self):
        return b2a_hex(self.data[0:4] + self.data[8:13])

    def write(self):
        '''
            Write the entire config block to chip. Does NOT lock it.
        '''
        assert self.data, "need read first"
        assert len(self.data) == 4 * 32

        zone = 0
        for n in range(16, 128, 4):
            if 84 <= n < 90:
                continue

            # must work on words, since can't write to most of the complete blocks.
            args = write_params(block=n // 32, offset=n // 4, is_config=True)
            try:
                x = self.ae_cmd(body=self.data[n:n + 4], **args)
            except:
                print("n=%d args=%r" % (n, args))
                raise

            assert x[0] == 0, 'fail 0x%x @ n=%d' % (x[0], n)

            #readback = dev.ae_cmd(opcode=OP.Read, p1=zone, p2=p2, resp_len=32)
            args['resp_len'] = 4
            args['opcode'] = OP.Read
            readback = self.ae_cmd(**args)
            assert readback == self.data[n:n + 4], 'bad r/b @ n=%d' % n

            self.reset_watchdog()

    def set_slot(self, n, slot_conf, key_conf):
        assert 0 <= n <= 15, n
        assert isinstance(slot_conf, SlotConfig)
        assert isinstance(key_conf, KeyConfig)

        self.data[20 + (n * 2):22 + (n * 2)] = slot_conf.pack()
        self.data[96 + (n * 2):98 + (n * 2)] = key_conf.pack()

    def set_combo(self, n, combo):
        self.set_slot(n, combo.sc, combo.kc)

    def get_combo(self, n):
        #  XXX broken
        from secel_config import ComboConfig, KeyConfig, SlotConfig

        rv = ComboConfig()
        blk = self.data
        rv.kc = KeyConfig.unpack(blk[96 + (2 * n):2 + 96 + (2 * n)])
        rv.sc = SlotConfig.unpack(blk[20 + (2 * n):2 + 20 + (2 * n)])
        return rv

    def set_otp_mode(self, read_only):
        # set OTPmode for consumption or read only
        # default is consumption.
        self.data[18] = 0xAA if read_only else 0x55

    def dump(self):
        from secel_config import secel_dump

        rnd = self.ae_cmd(opcode=OP.Random, resp_len=32, delay=24)
        secel_dump(self.data, rnd)

    def get_random(self):
        return self.ae_cmd(opcode=OP.Random, resp_len=32)

    def is_config_locked(self):
        "Is the config locked? Data and Slots might be unlocked still."
        return self.data[87] != 0x55

    def is_data_locked(self):
        "has data (+OTP) area been locked?"
        return self.data[86] != 0x55

    def LOCK(self,
             data=None,
             is_config=False,
             slot_num=None,
             datazone=False,
             no_crc=False,
             ecc_slots=[]):
        '''
            Lock the config area (default) or a specific slow or the OTP+Data area.
        '''
        if datazone and slot_num != None:
            # single slot of data area
            assert 0 <= slot_num < 16, slot_num
            if data == None:
                data = self.d_slot[slot_num]
            else:
                assert data == self.d_slot[
                    slot_num], "Not the data we think is there"
            assert data is not None
            mode = 0x2 | (slot_num << 2)
        elif is_config:
            assert not datazone and slot_num == None
            data = self.data
            assert len(data) == 128
            mode = 0x00
        elif datazone:
            '''
                "The slot contents are concatenated in numerical
                order to create the input to the CRC algorithm.
                Slots that are configured to contain an ECC private
                key are never included in the summary CRC calculation.
                The OTP zone is then concatenated after the last
                Data slot and the CRC value is calculated"
            '''
            assert not is_config and slot_num is None
            included = [i for i in range(16) if not i not in ecc_slots]
            data = [self.d_slot[i] for i in included]
            assert all(data), "Missing data some slot(s): %r" % (
                [n for n in included if not self.d_slot[n]])
            assert all(len(self.d_slot[i]) == slot_layout(i)[1] for i in included), \
                        repr([len(i) for i in self.d_slot])

            data = b''.join(data)

            # we're not supporting pre-loading OTP area yet, so better be blank
            data += b'\xff' * 64

            mode = 0x01
            if no_crc:
                mode |= 0x80
        else:
            raise ValueError("bad combo")

        chk = crc16w(data)

        rv = self.ae_cmd1(opcode=OP.Lock,
                          p1=mode,
                          p2=ustruct.unpack('<H', chk)[0],
                          delay=33)
        if rv:
            raise ChipErrorResponse(hex(rv))

        if datazone and slot_num != None:
            # check read-back
            self.read()
            assert self.is_slot_locked(
                slot_num), "read back not showing locked?"

    def write_data_slot(self, slot_num, data):
        "write into a specific data slot; which could be pubkey, cert, etc"
        assert 0 <= slot_num <= 15, n
        assert len(data) % 4 == 0

        # track it for later Lock command
        self.d_slot[slot_num] = data + (b'\xff' *
                                        (slot_layout(slot_num)[1] - len(data)))

        block = 0
        while len(data):
            args = write_params(slot=slot_num,
                                block=block,
                                offset=0,
                                is_data=True,
                                sz=0x80)
            #print("WRITE: %r data=%s" % (args, b2a_hex(data[0:32])))
            assert len(data) >= 32
            rv = self.ae_cmd1(body=data[0:32], **args)
            if rv:
                raise ChipErrorResponse("write @ blk=%d: 0x%02x" % (block, rv))

            data = data[32:]
            block += 1
            if 1 <= len(data) < 32:
                # pad out final write; it's easier than guessing if partial
                # write would be allowed
                data += b'\xff' * (32 - len(data))

    def get_info(self, mode=2):
        x = self.ae_cmd(opcode=OP.Info, p1=mode, p2=0, resp_len=4, delay=2)
        return InfoStat_unpack(x[0:2]) if mode == 2 else x

    def is_slot_locked(self, n):
        v = self.get_slot_locks()
        return not bool(v & (1 << n))

    def get_slot_locks(self):
        return ustruct.unpack('<H', self.data[88:90])[0]

    def get_valid_keys(self):
        # which key numbers does the chip consider valid right now.
        rv = []
        for i in range(16):
            x = self.ae_cmd(opcode=OP.Info, p1=1, p2=i, resp_len=4)[0]
            if x == 1:
                rv.append(i)
            else:
                assert x == 0
            #print("Info[key=%d] = %s" % (i, b2a_hex(x)))

        return rv

    def set_gpio(self, n):
        # 1=turn on green, 0=red light (if not yet setup)
        rv = self.ae_cmd(opcode=OP.Info, p1=3, p2=(2 | (n & 1)), resp_len=4)

        return rv[0]

    def get_gpio(self):
        rv = self.ae_cmd(opcode=OP.Info, p1=3, p2=0, resp_len=4)

        return rv[0]

    def load_nonce(self, mhash=None):
        "Set TempKey to a known, but randomly-based value"

        if mhash != None:
            # load with known value; won't work with some commands (ReqRandom=1)
            assert len(mhash) == 32

            rv = self.ae_cmd1(opcode=OP.Nonce, p1=3, p2=0, body=mhash)
            if rv:
                raise ChipErrorResponse(hex(rv))

        else:
            # A random number must be involved, so no choice in args to OP.Nonce here (ReqRandom).
            ch2 = random_bytes(20)
            rndout = self.ae_cmd(opcode=OP.Nonce,
                                 p1=0,
                                 p2=0,
                                 resp_len=32,
                                 body=ch2)

            # NOTE: response is the (old) contents of the RNG, not the TempKey value itself.
            assert len(rndout) == 32

            # TempKey on the chip will be set to the output of SHA256 over
            # a message composed of my challenge, the RNG and 3 bytes of constants:
            return sha256(bytes(rndout) + ch2 + b'\x16\0\0').digest()

    def generate_ec_privkey(self, priv_slot_num):
        '''
            Have the chip pick an EC key, write it and return public key
        '''

        # returns 64 bytes of public key, but saves it as well
        return self.ae_cmd(opcode=OP.GenKey,
                           p1=0x4,
                           p2=priv_slot_num,
                           resp_len=64)

    def write_ec_privkey(self, slot_num, secret, pre_auth=None):
        "write a known EC private key into a slot, verify it"
        assert len(secret) == 32

        if pre_auth: pre_auth()

        # doing an unencrypted, no-mac write.
        msg = (b'\0' * 4) + secret
        assert len(msg) == 36
        self.ae_cmd1(opcode=OP.PrivWrite, p1=0, p2=slot_num, body=msg)

        # get chip to make public part of it again
        if pre_auth: pre_auth()

        # and verify it by signing something.
        mhash = random_bytes(32)
        self.load_nonce(mhash)
        sig_rs = self.ae_cmd(opcode=OP.Sign, p1=0x80, p2=slot_num, resp_len=64)
        assert len(sig_rs) == 64

        skey = SigningKey.from_string(secret, curve=NIST256p, hashfunc=sha256)

        skey.verifying_key.verify_digest(sig_rs, mhash)

    def write_ec_pubkey(self, slot_num, pubxy, signkey=None, do_lock=False):
        "Write a known public key, and verify it is right."
        assert len(pubxy) == 64
        assert slot_num >= 8
        assert not self.is_slot_locked(slot_num)

        # "Public keys can be written directly to the EEPROM using Write command and are always
        #  72 bytes long, formatted as follows: 4 pad bytes, 32 bytes of X, four pad bytes,
        #  then 32 bytes of Y."
        # - putting the 0x50 marks it as "validated", which is a little bogus, but has
        #   nice side-effect of making the key show as "valid" in Info reponse.

        msg = b'\x50' + (b'\0' * 3) + pubxy[0:32] + b'\x50' + (
            b'\0' * 3) + pubxy[32:64]
        assert len(msg) == 72

        # change the pubkey
        self.write_data_slot(slot_num, msg)

        if signkey:
            # To an on-chip verify to check the pubkey is right.
            # NOTE: can only work if we allowed key to sign random things (we dont)
            self.do_verify(slot_num, signkey)

        if do_lock:
            self.LOCK(slot_num=slot_num, data=msg, datazone=True)

        return msg

    def do_verify(self, slot_num, signkey):
        # To an on-chip verify to check a pubkey is right.
        # - set TempKey to a known, but randomly-based value...
        challenge = self.load_nonce()

        # sign that "message"
        sig = signkey.sign_digest(challenge)
        assert len(sig) == 64

        # check we're still good. Watchdog failure here would be bad.
        info = self.get_info()
        assert info.TK_Valid == 1, repr(info)

        # p1=0="stored" mode
        try:
            rv = self.ae_cmd1(opcode=OP.Verify, p1=0, p2=slot_num, body=sig)

            if rv:
                raise ChipErrorResponse(hex(rv))
        except Exception as e:
            print("\nFAILED to verify key[%d]: %s\n" % (slot_num, e))
            #x = self.get_combo(slot_num)
            #print("[%d] %s %s" % (slot_num, x.sc, x.kc))
            raise

        # check it worked right.
        info = self.get_info()
        assert info.TK_Valid == 0  # it's consumed I suppose
        assert info.AuthKey == slot_num
        assert info.AuthValid == 1

    def do_checkmac(self, slot_num, hkey):
        "verify we know the SHA256 key in slot n"
        assert len(hkey) == 32

        # Note: cannot read back while data zone is unlocked, but we
        # can use the key right away in a CheckMac operation and that verifies
        # it real good.

        challenge = self.load_nonce()

        # 32 bytes of "client challenge" and 13 bytes of "other data" are needed, but
        # we have control over their contents.
        ch3 = b'0' * 32  # unused/padding
        od = random_bytes(13)
        msg = hkey + challenge + od[0:4] + (b'\0'*8) + od[4:7] + b'\xee' \
                    + od[7:11] + b'\x01\x23' + od[11:13]
        assert len(msg) == 32 + 32 + 4 + 8 + 3 + 1 + 4 + 2 + 2
        resp = sha256(msg).digest()
        body = ch3 + resp + od
        assert len(body) == 32 + 32 + 13
        # mode=p1 must be 0x01 ... for AuthKey effect to be applied
        rv = self.ae_cmd1(opcode=OP.CheckMac, p1=0x1, p2=slot_num, body=body)

        if rv == 1:
            raise WrongMacVerify()
        elif rv:
            raise ChipErrorResponse(hex(rv))

        info = self.get_info()
        #print("After CheckMac Info = %r" % info)
        #assert info.TK_Valid == 0, info           # zero=consumed, but sometimes 1 if used for copy
        assert info.AuthKey == slot_num, info
        assert info.AuthValid == 1, 'AuthValid clear: %r' % info

        self.reset_watchdog()

    def hmac(self, slot_num, challenge, diverse=True):
        assert len(challenge) == 32
        self.load_nonce(mhash=challenge)

        return self.ae_cmd(opcode=OP.HMAC,
                           p1=(1 << 2) | ((1 << 6) if diverse else 0),
                           p2=slot_num,
                           resp_len=32)

    def gendig_slot(self, slot_num, hkey, noMac=False):
        # Construct a digest on the device (and here) than depends on the secret
        # contents of a specific slot.
        assert len(hkey) == 32
        assert not noMac, "don't know how to handle noMac=1 on orig key"

        challenge = self.load_nonce()

        # using Zone=2="Data" => "KeyID specifies a slot in the Data zone"

        msg = hkey + b'\x15\x02' + ustruct.pack("<H", slot_num)
        msg += b'\xee\x01\x23' + (b'\0' * 25) + challenge
        assert len(msg) == 32 + 1 + 1 + 2 + 1 + 2 + 25 + 32

        rv = self.ae_cmd1(opcode=OP.GenDig, p1=0x2, p2=slot_num)
        if rv:
            raise ChipErrorResponse(hex(rv))

        self.reset_watchdog()

        return sha256(msg).digest()

    def read_encrypted(self, slot_num, read_kn, read_key):
        # use our knowledge of slot read_kn, to unlock and do encrypted-read of slot_num
        # - if slot not actually encrypted, will return garbage (no easy means to detect)
        dig = self.gendig_slot(read_kn, read_key)
        #print("After gendig:\n%r" % self.get_info())
        self.reset_watchdog()

        args = read_params(block=0,
                           slot=slot_num,
                           is_config=False,
                           is_data=True,
                           offset=0)
        rb = self.ae_cmd(opcode=OP.Read, **args)

        return bytes(a ^ b for a, b in zip(dig, rb))

    def write_encrypted(self, slot_num, write_kn, write_key, new_value):
        # use our knowledge of slot write_kn, to unlock and do encrypted-write into slot_num
        assert len(new_value) == 32
        assert len(write_key) == 32

        assert self.is_data_locked(
        ), "enc write w/ data unlocked writes garbage"

        dig = self.gendig_slot(write_kn, write_key)
        #print("After gendig:\n%r" % self.get_info())
        self.reset_watchdog()

        enc = bytes(a ^ b for a, b in zip(dig, new_value))

        args = write_params(slot=slot_num,
                            block=0,
                            offset=0,
                            is_data=True,
                            sz=0x80)
        #print("WRITE: %r data=%s" % (args, b2a_hex(data[0:32])))
        assert len(enc) == 32

        # "authorizing mac" is also required to be sent:
        # SHA-256(TempKey, Opcode, Param1, Param2, SN<8>, SN<0:1>, <25 bytes of zeros>, PlainTextData)
        msg = (dig + ustruct.pack('<bbH', OP.Write, args['p1'], args['p2']) +
               b'\xee\x01\x23' + (b'\0' * 25) + new_value)
        assert len(msg) == 32 + 1 + 1 + 2 + 1 + 2 + 25 + 32

        auth_mac = sha256(msg).digest()

        rv = self.ae_cmd1(body=enc + auth_mac, **args)
        if rv:
            raise ChipErrorResponse(hex(rv))

    def derive_key(self, kn, old_val=None):

        # random tempkey
        challenge = self.load_nonce()

        rv = self.ae_cmd1(opcode=OP.DeriveKey, p1=0x0, p2=kn, delay=51)
        if rv:
            raise ChipErrorResponse(hex(rv))

        if old_val is not None:
            # calc new key
            msg = (old_val + bytes([OP.DeriveKey, 0x0]) +
                   ustruct.pack("<H", kn) + b'\xee\x01\x23' + (b'\0' * 25) +
                   challenge)

            return sha256(msg).digest()

    def counter(self, idx, inc=False):
        assert 0 <= idx < 2, idx
        rv = self.ae_cmd(opcode=OP.Counter,
                         p1=0x0 if not inc else 0x1,
                         p2=idx,
                         resp_len=4)
        return ustruct.unpack("<I", rv)[0]
Exemple #28
0
class ArloRobot(object):

    # com packet sending
    def com(self, packet, ret):
        msg = ''
        for i in packet:
            msg = msg + i + ' '
        msg = msg + '\r'
        self.uart.write(msg)
        tinit = utime.ticks_ms()
        resp = ""

        if ret:
            while (utime.ticks_ms() - tinit) < 150:  # timeout of 1600us
                data = self.uart.read(1)
                if data is not None and data != b"\r":
                    resp = resp + str(data)[2:][:-1]
                elif data == b"\r":
                    break

            if resp is not None:
                resp = resp.split("xd6")[-1].split("xc3")[-1].split(" ")

                try:
                    resp = [int(i) for i in resp]
                except:
                    return resp

                if len(resp) != 2:
                    return resp[0]
                return resp
            return resp
        else:
            pass

    # set up/set down
    # serialid is defined as the ID of the serial bus from the
    # microcontroller, however tx and rx can be defined
    def __init__(self, serial_id=2, baudrate=19200, **kwargs):
        self.baudrate = baudrate
        self.serial_id = serial_id

        if "serial" in kwargs:
            self.uart = kwargs.get("serial")
        elif "tx" in kwargs and "rx" in kwargs:
            self.uart = UART(self.serial_id, self.baudrate)
            self.uart.init(
                self.baudrate,
                tx=kwargs.get("tx"),
                rx=kwargs.get("rx"),
                bits=8,
                parity=None,
                stop=1,
                txbuf=0,
            )
        else:
            self.uart = UART(self.serial_id, self.baudrate)
            self.uart.init(self.baudrate, bits=8, parity=None, stop=1, txbuf=0)

        self.com(["TXPIN", "CH2"], False)  # needed so that reading is possible
        self.com(["DEC"], False)
        self.com(["ECHO", "ON"], False)

    # end serial connection
    def end(self):
        self.uart.deinit()

    # -------------------------- movements methods------------------------

    # Turn command
    # motor_movements corresponds to the amount of encode positions
    # top_speed to the positions per second
    def turn(self, motor_movement, top_speed, ret=False):
        self.com(["TURN", str(motor_movement), str(top_speed)], ret)

    # arc turns the motors so that the platform moves along the arc of a circle
    # of a given radius with a speed and an angle
    def arc(self, radius, top_speed, angle, ret=False):
        self.com(["ARC", str(radius), str(top_speed), str(angle)], ret)

    # left/right -> -32767 to 32767
    # speed -> 1 to 32767
    def move(self, left, right, speed, ret=False):
        self.com(["MOVE", str(left), str(right), str(speed)], ret)

    # left/right -> -32767 to 32767
    def go_speed(self, left, right, ret=False):
        self.com(["GOSPD", str(left), str(right)], ret)

    # left/right -> -127 to 127
    def go(self, left, right, ret=False):
        self.com(["GO", str(left), str(right)], ret)

    def travel(self, distance, top_speed, angle, ret=False):
        self.com(["TRVL", str(distance), str(top_speed), str(angle)], ret)

    # --------------------------- information methods -----------------------

    def read_counts(self, ret=True):
        return self.com(["DIST"], ret)

    def read_left_counts(self, ret=True):
        return self.com(["DIST"], ret)[0]

    def read_right_counts(self, ret=True):
        return self.com(["DIST"], ret)[1]

    def read_left_speed(self, ret=True):
        return self.com(["SPD"], ret)[0]

    def read_right_speed(self, ret=True):
        return self.com(["SPD"], ret)[1]

    def read_head_angle(self, ret=True):
        data = self.com(["HEAD"], ret)
        try:
            if len(data) == 2:
                return int((data[1]))
            else:
                return int(data[0])
        except:
            return data

    def read_firmware_ver(self, ret=True):
        return self.com(["VER"], ret)

    def read_hardware_ver(self, ret=True):
        return self.com(["HWVER"], ret)

    def clear_counts(self, ret=True):
        return self.com(["RST"], ret)

    # ---------------------------- communication modes -----------------------

    def write_pulse_mode(self, ret=False):
        return self.com(["PULSE"], ret)

    def set_lf_mode(self, status, ret=False):
        return self.com(["SETLF", str(status)], ret)

    def set_hex_com(self, ret=False):
        return self.com(["HEX"], ret)

    def set_dec_com(self, ret=False):
        return self.com(["DEC"], ret)

    def set_echo_mode(self, status, ret=False):
        return self.com(["ECHO", str(status)], ret)

    def set_verbose_mode(self, status, ret=False):
        return self.com(["VERB", str(status)], ret)

    def set_rx_pin(self, pin, ret=False):
        return self.com(["RXPIN", str(pin)], ret)

    def set_tx_pin(self, pin, ret=False):
        return self.com(["TXPIN", str(pin)], ret)

    def set_baud_rate(self, baud, ret=False):
        return self.com(["BAUD", str(baud)], ret)

    def set_pwm_scale(self, scale, ret=False):
        return self.com(["SCALE", str(scale)], ret)

    def set_pace(self, pace, ret=False):
        return self.com(["PACE", str(pace)], ret)

    def set_hold(self, hold, ret=False):
        return self.com(["HOLD", str(baud)], ret)

    # -------------------------- closed loop constants ----------------------

    def set_ki_limit(self, limit, ret=False):
        return self.com(["KIP", str(limit)], ret)

    def set_ki_decay(self, decay, ret=False):
        return self.com(["KIT", str(decay)], ret)

    def set_kimax(self, maxim, ret=False):
        return self.com(["KIMAX", str(maxim)], ret)

    def set_ki_constant(self, constant, ret=False):
        return self.com(["KI", str(constant)], ret)

    def set_kp_constant(self, constant, ret=False):
        return self.com(["KP", str(constant)], ret)

    def set_acc_rate(self, acc, ret=False):
        return self.com(["ACC", str(acc)], ret)

    def set_ramp_rate(self, rate, ret=False):
        return self.com(["RAMP", str(rate)], ret)

    def set_live_zone(self, limit, ret=False):
        return self.com(["LZ", str(limit)], ret)

    def set_dead_zone(self, limit, ret=False):
        return self.com(["DZ", str(limit)], ret)

    def set_ppr(self, ppr, ret=False):
        return self.com(["PPR", str(ppr)], ret)

    # -------- config ----------
    def restore_config(self, ret=False):
        return self.com(["RESTORE"], ret)

    def read_config(self, command, ret=True):
        return self.com([comman], ret)
Exemple #29
0
class Player():
    def __init__(self, uart=None, busy_pin=None, config=True, volume=0.5):
        self._volume = None
        if uart is None:
            self.uart = UART(1, 9600)  # UART on
            self.uart.init(9600, bits=8, parity=None, stop=1)
        else:
            self.uart = uart
        if busy_pin is not None:
            busy_pin.init(mode=Pin.IN, pull=Pin.PULL_UP)
        self.busy_pin = busy_pin
        if config:
            self.config()
        if volume is not None:
            self.volume(volume)

    def command(self, CMD, Par1, Par2):
        self.awaitconfig()
        Checksum = -(Version_Byte + Command_Length + CMD + Acknowledge + Par1 +
                     Par2)
        HighByte, LowByte = split(Checksum)
        CommandLine = bytes([
            b & 0xFF for b in [
                Start_Byte, Version_Byte, Command_Length, CMD, Acknowledge,
                Par1, Par2, HighByte, LowByte, End_Byte
            ]
        ])
        self.uart.write(CommandLine)

    def config(self):
        self.configtime = ticks_ms()
        #self.reset()
        self.command(0x3F, 0x00, 0x00)

    def play(self, folderNum, trackNum):
        self.awaitconfig()
        self.playtime = ticks_ms()
        self.command(0x0F, folderNum, trackNum)

    def finish(self, folderNum, trackNum):
        self.play(folderNum, trackNum)
        while self.playing():
            sleep_ms(50)

    def playing(self):
        if self.busy_pin is not None:
            self.awaitplay()
            return self.busy_pin.value() == 0
        else:
            raise AssertionError(
                "No busy pin provided, cannot detect play status")

    def awaitconfig(self):
        if self.configtime is not None:
            kill_time(self.configtime, CONFIG_LATENCY)
        self.configtime = None

    def awaitplay(self):
        if self.playtime is not None:  # handle delay between playing and registering
            kill_time(self.playtime, PLAY_LATENCY)
        self.playtime = None

    def awaitvolume(self):
        if self.volumetime is not None:  # handle delay between playing and registering
            kill_time(self.volumetime, VOLUME_LATENCY)
        self.volumetime = None

    def repeat(self, repeat=True):
        self.awaitconfig()
        val = 1 if repeat else 0
        self.command(0x11, 0, val)

    def _gain(self, gain=1.0):
        self.awaitconfig()
        gain = float(clamp(gain, 0, 1.0))
        val = int(30.0 * gain)
        self.command(0x10, 0, val)

    def volume(self, volume=None):
        self.awaitconfig()
        if volume is None:
            return self._volume
        else:
            self._volume = float(clamp(volume, 0, 1.0))
            val = int(30.0 * self._volume)
            self.command(0x06, 0, val)
            self.volumetime = ticks_ms()

    def standby(self):
        self.awaitconfig()
        self.command(0x0A, 0x00, 0x00)

    def wake(self):
        self.awaitconfig()
        self.command(0x0B, 0x00, 0x00)

    def reset(self):
        self.awaitconfig()
        self.command(0x0C, 0x00, 0x00)
Exemple #30
0
if 'LaunchPad' in mch:
    uart_id_range = range(0, 2)
    uart_pins = [[('GP12', 'GP13'), ('GP12', 'GP13', 'GP7', 'GP6')], [('GP16', 'GP17'), ('GP16', 'GP17', 'GP7', 'GP6')]]
elif 'WiPy' in mch:
    uart_id_range = range(0, 2)
    uart_pins = [[('GP12', 'GP13'), ('GP12', 'GP13', 'GP7', 'GP6')], [('GP16', 'GP17'), ('GP16', 'GP17', 'GP7', 'GP6')]]
else:
    raise Exception('Board not supported!')

# just in case we have the repl duplicated on any of the uarts
os.dupterm(None)

for uart_id in uart_id_range:
    uart = UART(uart_id, 38400)
    print(uart)
    uart.init(57600, 8, None, 1, pins=uart_pins[uart_id][0])
    uart.init(baudrate=9600, stop=2, parity=UART.EVEN, pins=uart_pins[uart_id][1])
    uart.init(baudrate=115200, parity=UART.ODD, stop=0, pins=uart_pins[uart_id][0])
    uart = UART(baudrate=1000000)
    uart.sendbreak()

uart = UART(baudrate=1000000)
uart = UART()
print(uart)
uart = UART(baudrate=38400, pins=('GP12', 'GP13'))
print(uart)
uart = UART(pins=('GP12', 'GP13'))
print(uart)
uart = UART(pins=(None, 'GP17'))
print(uart)
uart = UART(baudrate=57600, pins=('GP16', 'GP17'))
Exemple #31
0
from machine import UART, I2C, Pin, SPI #gps
import ssd1306

##################inicializacion de modulos###################
# pantalla oled
vext = Pin(21, Pin.OUT)
vext.value(0)
rst = Pin(16, Pin.OUT)
rst.value(1)
scl = Pin(15, Pin.OUT, Pin.PULL_UP)
sda = Pin(4, Pin.OUT, Pin.PULL_UP)
i2c = I2C(scl=scl, sda=sda, freq=450000)
oled = ssd1306.SSD1306_I2C(128, 64, i2c, addr=0x3c)

try:
	oled.fill(0)
	# GPS
	gps = UART(2, 9600)
	gps.init(9600,bits=8,parity=None,stop=1,tx=5,rx=17)
	oled.text('gps..ok',0,0)
	oled.show()
	# acelerometro
	#mpu = mpu6050.MPU()
	# tarjeta SD
	#Pin(18,Pin.OUT,value=1) #para desactivar LoRa
	#spi = SPI(sck=Pin(23),miso=Pin(14),mosi=Pin(13))
	#sd = sdcard.SDCard(spi, Pin(2,Pin.OUT))
except:
	pass
	#mandar mensaje de error