Esempio n. 1
0
 def mount(self):
   try:
     self.sd = SDCard(slot=3)
     uos.mount(self.sd,"/sd")
     return True
   except:
     return False
async def play_wav():
    bck_pin = Pin(21) 
    ws_pin = Pin(22)  
    sdout_pin = Pin(27)
    
    # channelformat settings:
    #     mono WAV:  channelformat=I2S.ONLY_LEFT
    audio_out = I2S(
        I2S.NUM0, 
        bck=bck_pin, ws=ws_pin, sdout=sdout_pin, 
        standard=I2S.PHILIPS, 
        mode=I2S.MASTER_TX,
        dataformat=I2S.B16, 
        channelformat=I2S.ONLY_LEFT,
        samplerate=SAMPLE_RATE_IN_HZ,
        dmacount=10, dmalen=512)
    
    # configure SD card
    #   slot=2 configures SD card to use the SPI3 controller (VSPI), DMA channel = 2
    #   slot=3 configures SD card to use the SPI2 controller (HSPI), DMA channel = 1
    sd = SDCard(slot=3, sck=Pin(18), mosi=Pin(23), miso=Pin(19), cs=Pin(4))
    uos.mount(sd, "/sd")
    wav_file = '/sd/{}'.format(WAV_FILE)
    wav = open(wav_file,'rb')
    
    # advance to first byte of Data section in WAV file
    pos = wav.seek(44) 
    
    # allocate sample arrays
    #   memoryview used to reduce heap allocation in while loop
    wav_samples = bytearray(1024)
    wav_samples_mv = memoryview(wav_samples)
    
    print('Starting ... ')
    # continuously read audio samples from the WAV file 
    # and write them to an I2S DAC
    
    try:
        while True:
            num_read = wav.readinto(wav_samples_mv)
            num_written = 0
            # end of WAV file?
            if num_read == 0:
                # advance to first byte of Data section
                pos = wav.seek(44) 
            else:
                # loop until all samples are written to the I2S peripheral
                while num_written < num_read:
                    num_written += audio_out.write(wav_samples_mv[num_written:num_read], timeout=0)
            await asyncio.sleep_ms(10)
    except (KeyboardInterrupt, Exception) as e:
        print('caught exception {} {}'.format(type(e).__name__, e))
        raise
    finally:
        wav.close()
        uos.umount("/sd")
        sd.deinit()
        audio_out.deinit()
        print('Done')
Esempio n. 3
0
 def start(self):
     try:
         self.sdcard = SDCard(slot=2,
                              miso=Pin(self.miso),
                              mosi=Pin(self.mosi),
                              sck=Pin(self.sck),
                              cs=Pin(self.cs))
         self.inited = True
         self.mount()
     except Exception as e:
         sys.print_exception(e)
         print('sd init failure')
Esempio n. 4
0
    def _init_card(self):
        try:
            if self._card is None:
                self._card = SDCard(slot=SLOT,
                                    mosi=PIN_MOSI,
                                    miso=PIN_MISO,
                                    sck=PIN_SCK,
                                    cs=PIN_CS)
        except Exception:
            raise Exception("Card reader not present")

        return self._card
Esempio n. 5
0
class SD:
    def __init__(self,
                 miso=PIN_MISO,
                 mosi=PIN_MOSI,
                 sck=PIN_SCK,
                 cs=PIN_CS,
                 sd_path=SD_PATH):
        self.miso = miso
        self.mosi = mosi
        self.cs = cs
        self.sck = sck
        self.sdcard = None
        self.sd_path = sd_path
        self.inited = False
        self.mounted = False

    def start(self):
        try:
            self.sdcard = SDCard(slot=2,
                                 miso=Pin(self.miso),
                                 mosi=Pin(self.mosi),
                                 sck=Pin(self.sck),
                                 cs=Pin(self.cs))
            self.inited = True
            self.mount()
        except Exception as e:
            sys.print_exception(e)
            print('sd init failure')

    def mount(self):
        try:
            os.mount(self.sdcard, self.sd_path)
            self.mounted = True
        except Exception as e:
            sys.print_exception(e)
            print('sd mount failure')

    def stop(self):
        if self.mounted:
            self.mounted = False
            try:
                os.umount(self.sd_path)
            except Exception as e:
                sys.print_exception(e)
                print('sd umount failure')
        if self.inited:
            try:
                self.sdcard.deinit()
            except Exception as e:
                sys.print_exception(e)
                print('sd deinit failure')
Esempio n. 6
0
class SD:
    def __init__(self, slot=2, pin=4) -> None:
        self.sd = SDCard(slot=slot, cs=Pin(pin))

    def __del__(self):
        self.sd.__del__()

    def deinit(self):
        self.sd.deinit()

    def mount(self, path="/sd"):
        mount(self.sd, path)

    def umount(self, path="/sd"):
        umount(path)
Esempio n. 7
0
def mount():
  global SD,spi
  try: # ESP32
    from machine import SDCard
    SD=SDCard(slot=3)
    os.mount(SD,"/sd")
  except:
    try: # ESP32-S2
      import sdpin
      from sdcard import SDCard
      from machine import SPI
      spi=SPI(sck=Pin(sdpin.clk), mosi=Pin(sdpin.cmd), miso=Pin(sdpin.d0))
      SD=SDCard(spi,Pin(sdpin.d3))
      os.mount(SD,"/sd")
    except:
      print("mount failed")
      return False
  return True
 def __init__(self):
     try:
         os.mount(
             SDCard(slot=3,
                    miso=Pin(12),
                    mosi=Pin(13),
                    sck=Pin(14),
                    cs=Pin(15)), "/sd")
     except:
         print("Sd card could not be read")
Esempio n. 9
0
def run():
    # some SD cards won't work in 4-bit mode unless freq() is explicitely set
    freq(240 * 1000 * 1000)  # 80/160/240 MHz, faster CPU = faster SD card
    #sd=SDCard(slot=3) # 1-bit mode
    sd = SDCard()  # 4-bit mode
    mount(sd, "/sd")
    print(listdir("/sd"))
    f = open("/sd/long_file.bin", "rb")  # any 1-10 MB long file
    b = bytearray(16 * 1024)
    i = 0
    t1 = ticks_ms()
    while f.readinto(b):
        i += 1
    t2 = ticks_ms()
    print("%d KB in %d ms => %d KB/s file read" %
          (i * len(b) // 1024, t2 - t1, 1000 * i * len(b) // 1024 //
           (t2 - t1)))
    f.close()
    umount("/sd")
    i = 0
    t1 = ticks_ms()
    while i < 256:
        sd.readblocks(i, b)
        i += 1
    t2 = ticks_ms()
    print("%d KB in %d ms => %d KB/s raw sector read" %
          (i * len(b) // 1024, t2 - t1, 1000 * i * len(b) // 1024 //
           (t2 - t1)))
    sd.deinit()
Esempio n. 10
0
def init():
    global __sdcard
    if __sdcard == None:
        try:
            sd = SDCard(
                slot=3,
                width=1,
                sck=Pin(PIN_SD_SCK),
                miso=Pin(PIN_SD_MISO),
                mosi=Pin(PIN_SD_MOSI),
                cs=Pin(PIN_SD_CS),
                # freq=20_000_000
            )
            __sdcard = __SDCardBlockDevice(sd)
        except: pass
Esempio n. 11
0
def mount_sdcard(slot_num, mount_point):
    global SDCARD_MOUNTED
    sdcard = SDCard(slot=slot_num)
    tries_remaining = 10
    while tries_remaining:
        try:
            mount(sdcard, mount_point)
        except OSError as e:
            print('Could not mount SD Card: OSError {}'.format(e))
        else:
            print('Mounted SD Card at: {}'.format(mount_point))
            SDCARD_MOUNTED = True
            break
        tries_remaining -= 1
        if tries_remaining == 0:
            break
        print('Trying again to mount SD Card...')
        sleep(1)
Esempio n. 12
0
from machine import Pin, I2C, SDCard, freq
from os import mount
import time, ntptime, mcp7940, ecp5

freq(240 * 1000 * 1000)
sd = SDCard(slot=3)  # 1-bit mode
mount(sd, "/sd")
ecp5.prog("/sd/rtc/ulx3s_12f_i2c_bridge.bit")

i2c = I2C(sda=Pin(16), scl=Pin(17), freq=400000)
mcp = mcp7940.MCP7940(i2c)

mcp.control = 0
mcp.trim = -29
#mcp.battery=1
#print("battery %s" % ("enabled" if mcp.battery else "disabled"))
print("trim %+d ppm" % mcp.trim)
print("control 0x%02X" % mcp.control)
print("setting time.localtime() to NTP time using ntptime.settime()")
ntptime.settime()
print("after NTP, time.localtime() reads:")
print(time.localtime())
print("setting mcp.time=time.localtime()")
mcp.stop()
mcp.time = time.localtime()
print("after setting:")
print("battery %s" % ("enabled" if mcp.battery else "disabled"))
print("mcp.time reads:")
# Read time after setting it, repeat to see time incrementing
for i in range(3):
    print(mcp.time)
Esempio n. 13
0
import uos
import time
import camera

from machine import SDCard
uos.mount(SDCard(), '/sd')
uos.chdir('sd')
camera.init(0, format=camera.JPEG)

i = 0
while i < 10000:
    buf = camera.capture()
    imgname = str(i) + ".jpg"
    img = open(imgname, 'w')
    img.write(buf)
    img.close()
    time.sleep(1)
    i += 1
Esempio n. 14
0
# This file is executed on every boot (including wake-boot from deepsleep)
from gc import collect
from esp import osdebug
from time import sleep
from ujson import load
import webrepl
from uos import mount, umount
from machine import unique_id, SDCard

osdebug(None)
collect()

try:
	mount(SDCard(slot=2, width=1, sck=14, miso=15, mosi=13, cs=5), "/fc")
	SD=True
	print("SD mounted")
except Exception as e:
	SD=False
	print("SD not mounted")
	
def readwificfg(): 
	try:
		file_name = "/fc/wifi.json"
		with open(file_name) as json_data_file:
			data = load(json_data_file)
		return data
	except Exception as e:
		print(repr(e))
		return None
def get_id():
	x = [hex(int(c)).replace("0x","") for c in unique_id()]
Esempio n. 15
0
def mount():
    """ Setup sd card object and mount to file system. """
    sd = SDCard(slot=COMM_SLOT, sck=P_SCK, miso=P_MISO, mosi=P_MOSI, cs=P_CS)
    os.mount(sd, ROOT)
    return sd
Esempio n. 16
0
        ads_address = i
        break
del found

# adc
import ads1015
ads = ads1015.ADS1015(i2c, ads_address, gain=1)

# mcp23017
import mcp23017
mcp = mcp23017.MCP23017(i2c, mcp_address)

# sd card
import uos as os
from machine import SDCard
sd = SDCard(slot=2)
sd_cd = Pin(33, Pin.IN)

# if sd card detect pin is LOW, a card is inserted
if sd_cd.value() == 0:
    try:
        print('Found SD card {}'.format(sd.info()))
        os.mount(sd, '/sd')
        print('Mounted SD card at /sd')
    except OSError:
        print('Failed to mount SD card')
else:
    print('SD card not inserted')

# deinit sd with
# os.umount('/sd')
Esempio n. 17
0
 def __init__(self, slot=2, pin=4, mount_folder="/sd") -> None:
     self.__sd = SDCard(slot=slot, cs=Pin(pin))
Esempio n. 18
0
                (addr >> 8) & 0xFF, addr & 0xFF
            ]))
        self.spi.write(data)
        self.cs.off()
        self.ctrl(4)
        self.ctrl(0)


def peek(addr, length=1):
    return run.peek(addr, length)


def poke(addr, data):
    run.poke(addr, data)


#bitstream="/sd/mac/bitstreams/ulx3s_v20_85f_mac128.bit"
bitstream = "/xyz.bit"
try:
    freq(240 * 1000 * 1000)  # 80/160/240 MHz, faster CPU = faster SD card
    #os.mount(SDCard(slot=3),"/sd") # 1-bit SD mode
    os.mount(
        SDCard(), "/sd"
    )  # 4-bit SD mode (mac bitstream must be flashed or already loaded)
    import ecp5
    ecp5.prog(bitstream)
except:
    print(bitstream + " file not found")
gc.collect()
run = osd()
Esempio n. 19
0
                ws=ws_pin,
                sdout=sdout_pin,
                standard=I2S.PHILIPS,
                mode=I2S.MASTER_TX,
                dataformat=I2S.B16,
                channelformat=I2S.ONLY_LEFT,
                samplerate=SAMPLE_RATE_IN_HZ,
                dmacount=10,
                dmalen=512)

# configure SD card:
# See [docs](https://docs.micropython.org/en/latest/library/machine.SDCard.html#esp32) for
# recommended pins depending on the chosen slot.
#   slot=2 configures SD card to use the SPI3 controller (VSPI), DMA channel = 2
#   slot=3 configures SD card to use the SPI2 controller (HSPI), DMA channel = 1
sd = SDCard(slot=2, sck=Pin(18), mosi=Pin(23), miso=Pin(19), cs=Pin(5))
uos.mount(sd, "/sd")
wav_file = '/sd/{}'.format(WAV_FILE)
wav = open(wav_file, 'rb')

# advance to first byte of Data section in WAV file
pos = wav.seek(44)

# allocate sample arrays
#   memoryview used to reduce heap allocation in while loop
wav_samples = bytearray(1024)
wav_samples_mv = memoryview(wav_samples)

print('Starting')
# continuously read audio samples from the WAV file
# and write them to an I2S DAC
Esempio n. 20
0
#   is called when the buffer supplied to read_into() is filled

import uos
import time
from machine import Pin
from machine import I2S

if uos.uname().machine.find("PYBv1") == 0:
    pass
elif uos.uname().machine.find("PYBD") == 0:
    import pyb
    pyb.Pin("EN_3V3").on()  # provide 3.3V on 3V3 output pin
    uos.mount(pyb.SDCard(), "/sd")
elif uos.uname().machine.find("ESP32") == 0:
    from machine import SDCard
    sd = SDCard(slot=3, sck=Pin(18), mosi=Pin(23), miso=Pin(19), cs=Pin(5))
    uos.mount(sd, "/sd")
else:
    print("Warning: program not tested with this board")

# ======= AUDIO CONFIGURATION =======
WAV_FILE = "mic.wav"
WAV_SAMPLE_SIZE_IN_BITS = 16
FORMAT = I2S.MONO
SAMPLE_RATE_IN_HZ = 22050
# ======= AUDIO CONFIGURATION =======

# ======= I2S CONFIGURATION =======
SCK_PIN = 13
WS_PIN = 14
SD_PIN = 34
Esempio n. 21
0
    'bsize',
    'frsize',
    'blocks',
    'bfree',
    'bavail',
    'files',
    'ffree',
]
info = dict(zip(statvfs_fields, os.statvfs('/flash')))
print(info)
print(info['bsize'] * info['bfree'])

import uos
from machine import SDCard

sd = SDCard(slot=2, mosi=23, miso=19, sck=18, cs=4)
uos.mount(sd, "/sd")
print(uos.listdir('/sd/'))

import network

wlan = network.WLAN(network.STA_IF)  # create station interface
print(wlan.active(True))  # activate the interface
print(wlan.scan())  # scan for access points
print(wlan.isconnected())  # check if the station is connected to an AP
print(wlan.connect('ChinaDaddy', 'Mdzz7788'))  # connect to an AP
print(wlan.config('mac'))  # get the interface's MAC address
print(wlan.ifconfig())  # get the interface's IP/netmask/gw/DNS addresses

# from machine import RTC
Esempio n. 22
0
class CardManager:
    """
    High level auto-mounting SD Card manager
    """
    def __init__(self, directory="/sd"):
        self._card = None
        self._directory = directory

        if Helpers.exists(self._directory) and \
                not Helpers.is_dir(self._directory):
            raise Exception("Cannot mount {}".format(self._directory))

        if not Helpers.exists(self._directory):
            uos.mkdir(self._directory)

        # Setup and IRQ on the CD line to auto-mount/dismount the sdcard
        pin = Pin(PIN_CD, Pin.IN, Pin.PULL_UP)
        pin.irq(trigger=Pin.IRQ_FALLING | Pin.IRQ_RISING,
                handler=self._card_state_change)
        # These are for debouncing the card detect signal
        self._debounce_timer = None
        self._debounce = False

        self._card_state_change(pin)

    def is_card_present(self):
        return bool(self._card is not None)

    def _remove_debounce(self, test):
        self._debounce = False

    def _init_card(self):
        try:
            if self._card is None:
                self._card = SDCard(slot=SLOT,
                                    mosi=PIN_MOSI,
                                    miso=PIN_MISO,
                                    sck=PIN_SCK,
                                    cs=PIN_CS)
        except Exception:
            raise Exception("Card reader not present")

        return self._card

    def _deinit_card(self):
        self._card.deinit()
        self._card = None

    def _card_state_change(self, pin):
        """
        Need to debounce this
        :param pin:
        :return:
        """
        if self._debounce:
            return

        self._debounce = True
        self._debounce_timer = Timer(-1)
        self._debounce_timer.init(period=DEBOUNCE_TIME,
                                  mode=Timer.ONE_SHOT,
                                  callback=self._remove_debounce)

        irq_state = disable_irq()

        if pin.value():  # No card present
            if self._card:  # Card may not be present on boot
                enable_irq(irq_state)
                uos.umount(self._directory)
                irq_state = disable_irq()
                self._deinit_card()
        else:
            try:
                card = self._init_card()
                enable_irq(irq_state)
                uos.mount(card, self._directory)
                irq_state = disable_irq()
            except OSError:  # Mount issue, probably EPERM
                pass

        enable_irq(irq_state)
Esempio n. 23
0
# Drum loop from Zapsplat.com:
# https://www.zapsplat.com/sound-effect-category/loops/

# Setup:
# copy wavplayer.py to your filesystem
# copy .wav files to a SD card

import os
import time
from machine import Pin
from wavplayer import WavPlayer

# configure and mount SD card
from machine import SDCard
sd = SDCard(slot=2)  # sck=18, mosi=23, miso=19, cs=5
os.mount(sd, "/sd")

# list files to your SD card
os.listdir('/sd')
# ['fart.wav', 'drum_loop_1.wav', 'drum_loop_3.wav', 'drum_loop_3.wav']

# adjust the gain (volume)
# gain = Pin(14)
# gain.init(Pin.IN, pull=Pin.PULL_DOWN) # gain 5: louder
# gain.init(Pin.OUT, value=0)           # gain 4: loud
# gain.init(Pin.IN, pull=None)          # gain 3: middle
# gain.init(Pin.OUT, value=1)           # gain 2: quiet
# gain.init(Pin.IN, pull=Pin.PULL_UP)   # gain 1: quieter

# init WavPlayer
Esempio n. 24
0
from machine import SDCard
import uos
uos.mount(SDCard(slot=2, mosi=15, miso=2, sck=14, cs=13), "/sd")

Esempio n. 25
0
import sys
import mimxrt
from machine import Pin

bdev = mimxrt.Flash()
try:
    vfs = os.VfsLfs2(bdev, progsize=256)
except:
    os.VfsLfs2.mkfs(bdev, progsize=256)
    vfs = os.VfsLfs2(bdev, progsize=256)
os.mount(vfs, "/flash")
os.chdir("/flash")
sys.path.append("/flash")
sys.path.append("/flash/lib")

# do not mount the SD card if SKIPSD exists.
try:
    os.stat("SKIPSD")
except:
    try:
        from machine import SDCard

        sdcard = SDCard(1)

        fat = os.VfsFat(sdcard)
        os.mount(fat, "/sdcard")
        os.chdir("/sdcard")
        sys.path.append("/sdcard")
    except:
        pass  # Fail silently
Esempio n. 26
0
File: phlox.py Progetto: scy/jessie
    def __init__(self,
                 pi_set_pin=5,
                 pi_unset_pin=33,
                 pi_powered_pin=25,
                 pi_powered_inv=False,
                 pi_heartbeat_pin=26,
                 pi_shutdown_pin=27,
                 pi_shutdown_inv=True,
                 votronic_port=2,
                 votronic_de_pin=4,
                 votronic_de_inv=False,
                 votronic_re_pin=2,
                 votronic_re_inv=True):
        # Mount the SD card and open a log file for debugging.
        self.logfile = None
        try:
            os.mount(SDCard(slot=3, sck=14, miso=12, mosi=13, cs=15), '/sd')
            self.logfile = open('/sd/phlox.log', 'a')
        except Exception as e:
            print_exception(e)
        self.log('Phlox initializing...')

        # We're using the Perthensis scheduler for multitasking.
        self.sch = sch = Scheduler()

        # Raspberry Pi controller object.
        # It will automatically switch the Pi on when initializing.
        self.pi = Pi(
            Signal(pi_powered_pin, Pin.IN, invert=pi_powered_inv),
            # Signal class inverts the constructor value if invert is True.
            Signal(pi_shutdown_pin, Pin.OUT, invert=pi_shutdown_inv, value=0),
            Signal(pi_heartbeat_pin, Pin.IN, Pin.PULL_DOWN),
            LatchingRelay(pi_set_pin, pi_unset_pin),
            sch,
            self.log,
        )

        # Default sleep state is "enable everything".
        self.set_sleepstate(0)

        # Initialize Votronic RS485 interface via Arduino MKR 485 shield.
        self.votronic = microtonic.UART(
            votronic_port,
            Signal(votronic_re_pin, Pin.OUT, invert=votronic_re_inv),
            Signal(votronic_de_pin, Pin.OUT, invert=votronic_de_inv),
        )
        self.votronic.on_packet = self.votronic_packet
        sch(self.votronic.read)

        # Prepare WLAN and MQTT.
        self.wlan = self.mqtt = None
        try:
            with open('wlan.json') as f:
                self.wlan = WLANClient(**json.load(f))
        except Exception as e:
            print_exception(e)

        if self.wlan is not None:
            # Add WLAN client to scheduler.
            sch(self.wlan.watch)
            # Set up MQTT.
            self.mqtt = MQTTClient('10.115.106.254',
                                   client_id='phlox',
                                   keepalive=30)
            self.mqtt.set_last_will('jessie/phlox/up', '0', True)
            self.mqtt.on_connect = self.mqtt_connected
            self.mqtt.set_callback(self.mqtt_msg)
            self.mqtt.subscribe('jessie/sleepstate')
            sch(self.mqtt.watch)

        self.log('Initialized.')
Esempio n. 27
0
        self.spi_freq = const(100000)
        self.init_spi()
        s = ld_ti99_4a.ld_ti99_4a(self.spi, self.cs)
        print("Saving memory from {} length {} file: {}".format(
            addr, length, filename))
        s.save_stream(open(filename, "wb"), addr, length)
        del s
        self.spi_freq = old_freq
        self.init_spi()
        gc.collect()


# FPGA init function not part of class.
def load_fpga():
    fpga_config_file = "/sd/ti99_4a/bitstreams/ti994a_ulx3s.bit"
    print("FPGA file: {}".format(fpga_config_file))
    ecp5.prog(fpga_config_file)  # ulx3s_85f_spi_ti99_4a.bit")
    gc.collect()


def reset():
    import machine
    machine.reset()


os.mount(SDCard(slot=3), "/sd")
load_fpga()

run = osd()
run.load_roms()
Esempio n. 28
0
    print("SD card did not mount correctly")
    # TODO: add LED sigal from board to signify this
    try:
        umount("/sdcard")
    except OSError as e:
        # TODO: add LED signal from board to signify this
        print("Reinsert SD Card in SD Card reader")
        # TODO: remove sleep once LED signal is done
        # sleep gives time to read comment before reseting the board
        sleep(3)
    reset()


# mount SD card
sd_gdt = GDT(2, station, func=sd_gdt_func)
mount(SDCard(slot=3), "/sdcard")
sd_gdt.deinit_timer()
del sd_gdt
collect()

config_file = "/sdcard/pmt.conf"
default = "/sdcard/pmt.log"
wifi = "/sdcard/wifi.log"
archive = "/sdcard/data.log"
unsent = "/sdcard/buffer.log"
blacklist = "/sdcard/blacklist.log"
current_ap = "/sdcard/SSID.log"
unsent_buffer_ptr = "/sdcard/buffer_pointer.log"

# create file for initial read
with open(blacklist, "a+"):
Esempio n. 29
0
class FTP_client:

  def __init__(self, ftpsocket):
    global AP_addr, STA_addr
    self.command_client, self.remote_addr = ftpsocket.accept()
    self.remote_addr = self.remote_addr[0]
    self.command_client.settimeout(_COMMAND_TIMEOUT)
    log_msg(1, "FTP Command connection from:", self.remote_addr)
    self.command_client.setsockopt(socket.SOL_SOCKET,
                                   _SO_REGISTER_HANDLER,
                                   self.exec_ftp_command)
    self.command_client.sendall("220 Hello, this is the ULX3S.\r\n")
    self.cwd = '/'
    self.fromname = None
    # self.logged_in = False
    self.act_data_addr = self.remote_addr
    self.DATA_PORT = 20
    self.active = True
    # check which interface was used by comparing the caller's ip
    # adress with the ip adresses of STA and AP; consider netmask;
    # select IP address for passive mode
    if ((AP_addr[1] & AP_addr[2]) ==
       (num_ip(self.remote_addr) & AP_addr[2])):
        self.pasv_data_addr = AP_addr[0]
    elif ((STA_addr[1] & STA_addr[2]) ==
          (num_ip(self.remote_addr) & STA_addr[2])):
        self.pasv_data_addr = STA_addr[0]
    elif ((AP_addr[1] == 0) and (STA_addr[1] != 0)):
        self.pasv_data_addr = STA_addr[0]
    elif ((AP_addr[1] != 0) and (STA_addr[1] == 0)):
        self.pasv_data_addr = AP_addr[0]
    else:
        self.pasv_data_addr = "0.0.0.0"  # Invalid value

  def send_list_data(self, path, data_client, full):
    try:
      for fname in uos.listdir(path):
        data_client.sendall(self.make_description(path, fname, full))
    except:  # path may be a file name or pattern
      path, pattern = self.split_path(path)
      try:
        for fname in uos.listdir(path):
          if self.fncmp(fname, pattern):
            data_client.sendall(
              self.make_description(path, fname, full))
      except:
          pass

  def make_description(self, path, fname, full):
    global _month_name
    if full:
      stat = uos.stat(self.get_absolute_path(path, fname))
      file_permissions = ("drwxr-xr-x"
                          if (stat[0] & 0o170000 == 0o040000)
                          else "-rw-r--r--")
      file_size = stat[6]
      tm = localtime(stat[7])
      if tm[0] != localtime()[0]:
        description = "{} 1 owner group {:>10} {} {:2} {:>5} {}\r\n".\
          format(file_permissions, file_size,
                 _month_name[tm[1]], tm[2], tm[0], fname)
      else:
        description = "{} 1 owner group {:>10} {} {:2} {:02}:{:02} {}\r\n".\
          format(file_permissions, file_size,
                 _month_name[tm[1]], tm[2], tm[3], tm[4], fname)
    else:
      description = fname + "\r\n"
    return description

  def send_file_data(self, path, data_client):
    with open(path,"rb") as file:
      chunk = file.read(_CHUNK_SIZE)
      while len(chunk) > 0:
        data_client.sendall(chunk)
        chunk = file.read(_CHUNK_SIZE)
      data_client.close()

  def save_file_data(self, path, data_client, mode):
    with open(path, mode) as file:
      chunk = data_client.recv(_CHUNK_SIZE)
      while len(chunk) > 0:
        file.write(chunk)
        chunk = data_client.recv(_CHUNK_SIZE)
      data_client.close()

  def get_absolute_path(self, cwd, payload):
    # Just a few special cases "..", "." and ""
    # If payload start's with /, set cwd to /
    # and consider the remainder a relative path
    if payload.startswith('/'):
      cwd = "/"
    for token in payload.split("/"):
      if token == '..':
        cwd = self.split_path(cwd)[0]
      elif token != '.' and token != '':
        if cwd == '/':
          cwd += token
        else:
          cwd = cwd + '/' + token
    return cwd

  def split_path(self, path):  # instead of path.rpartition('/')
    tail = path.split('/')[-1]
    head = path[:-(len(tail) + 1)]
    return ('/' if head == '' else head, tail)

  # compare fname against pattern. Pattern may contain
  # the wildcards ? and *.
  def fncmp(self, fname, pattern):
    pi = 0
    si = 0
    while pi < len(pattern) and si < len(fname):
      if (fname[si] == pattern[pi]) or (pattern[pi] == '?'):
        si += 1
        pi += 1
      else:
        if pattern[pi] == '*':  # recurse
          if pi == len(pattern.rstrip("*?")):  # only wildcards left
            return True
          while si < len(fname):
            if self.fncmp(fname[si:], pattern[pi + 1:]):
              return True
            else:
              si += 1
          return False
        else:
          return False
    if pi == len(pattern.rstrip("*")) and si == len(fname):
      return True
    else:
      return False

  def open_dataclient(self):
    if self.active:  # active mode
      data_client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
      data_client.settimeout(_DATA_TIMEOUT)
      data_client.connect((self.act_data_addr, self.DATA_PORT))
      log_msg(1, "FTP Data connection with:", self.act_data_addr)
    else:  # passive mode
      data_client, data_addr = datasocket.accept()
      log_msg(1, "FTP Data connection with:", data_addr[0])
    return data_client

  def mount(self):
    try:
      self.sd = SDCard(slot=3)
      uos.mount(self.sd,"/sd")
      return True
    except:
      return False

  def umount(self):
    try:
      uos.umount("/sd")
      try:
        self.sd.deinit()
        del self.sd
      except:
        pass
      # let all SD pins be inputs
      for i in bytearray([2,4,12,13,14,15]):
        p = Pin(i,Pin.IN)
        a = p.value()
        del p, a
      return True
    except:
      return False

  def exec_ftp_command(self, cl):
    global datasocket
    global client_busy
    global my_ip_addr

    try:
      collect()

      data = cl.readline().decode("utf-8").rstrip("\r\n")

      if len(data) <= 0:
          # No data, close
          # This part is NOT CLEAN; there is still a chance that a
          # closing data connection will be signalled as closing
          # command connection
          log_msg(1, "*** No data, assume QUIT")
          close_client(cl)
          return

      if client_busy:  # check if another client is busy
          cl.sendall("400 Device busy.\r\n")  # tell so the remote client
          return  # and quit
      client_busy = True  # now it's my turn

      # check for log-in state may done here, like
      # if self.logged_in == False and not command in\
      #    ("USER", "PASS", "QUIT"):
      #    cl.sendall("530 Not logged in.\r\n")
      #    return

      command = data.split()[0].upper()
      payload = data[len(command):].lstrip()  # partition is missing
      path = self.get_absolute_path(self.cwd, payload)
      log_msg(1, "Command={}, Payload={}".format(command, payload))

      if command == "USER":
        # self.logged_in = True
        cl.sendall("230 Logged in.\r\n")
        # If you want to see a password,return
        #   "331 Need password.\r\n" instead
        # If you want to reject an user, return
        #   "530 Not logged in.\r\n"
      elif command == "PASS":
        # you may check here for a valid password and return
        # "530 Not logged in.\r\n" in case it's wrong
        # self.logged_in = True
        cl.sendall("230 Logged in.\r\n")
      elif command == "SYST":
        cl.sendall("215 UNIX Type: L8\r\n")
      elif command in ("TYPE", "NOOP", "ABOR"):  # just accept & ignore
        cl.sendall('200 OK\r\n')
      elif command == "QUIT":
        cl.sendall('221 Bye.\r\n')
        close_client(cl)
      elif command == "PWD" or command == "XPWD":
        cl.sendall('257 "{}"\r\n'.format(self.cwd))
      elif command == "CWD" or command == "XCWD":
        try:
          if (uos.stat(path)[0] & 0o170000) == 0o040000:
            self.cwd = path
            cl.sendall('250 OK\r\n')
          else:
            cl.sendall('550 Fail\r\n')
        except:
          cl.sendall('550 Fail\r\n')
      elif command == "PASV":
        cl.sendall('227 Entering Passive Mode ({},{},{}).\r\n'.format(
          self.pasv_data_addr.replace('.', ','),
          _DATA_PORT >> 8, _DATA_PORT % 256))
        self.active = False
      elif command == "PORT":
        items = payload.split(",")
        if len(items) >= 6:
          self.act_data_addr = '.'.join(items[:4])
          if self.act_data_addr == "127.0.1.1":
            # replace by command session addr
            self.act_data_addr = self.remote_addr
          self.DATA_PORT = int(items[4]) * 256 + int(items[5])
          cl.sendall('200 OK\r\n')
          self.active = True
        else:
            cl.sendall('504 Fail\r\n')
      elif command == "LIST" or command == "NLST":
        if payload.startswith("-"):
          option = payload.split()[0].lower()
          path = self.get_absolute_path(
                 self.cwd, payload[len(option):].lstrip())
        else:
          option = ""
        try:
          data_client = self.open_dataclient()
          cl.sendall("150 Directory listing:\r\n")
          self.send_list_data(path, data_client,
                              command == "LIST" or 'l' in option)
          cl.sendall("226 Done.\r\n")
          data_client.close()
        except:
          cl.sendall('550 Fail\r\n')
          if data_client is not None:
            data_client.close()
      elif command == "RETR":
        try:
          data_client = self.open_dataclient()
          cl.sendall("150 Opened data connection.\r\n")
          self.send_file_data(path, data_client)
          # if the next statement is reached,
          # the data_client was closed.
          data_client = None
          cl.sendall("226 Done.\r\n")
        except:
          cl.sendall('550 Fail\r\n')
          if data_client is not None:
            data_client.close()
      elif command == "STOR" or command == "APPE":
        result = False
        try:
          data_client = self.open_dataclient()
          cl.sendall("150 Opened data connection.\r\n")
          if path == "/fpga":
            import ecp5
            ecp5.prog_stream(data_client,_CHUNK_SIZE)
            result = ecp5.prog_close()
            data_client.close()
          elif path.startswith("/flash@"):
            import ecp5
            dummy, addr = path.split("@")
            addr = int(addr)
            result = ecp5.flash_stream(data_client,addr)
            ecp5.flash_close()
            del addr, dummy
            data_client.close()
          elif path.startswith("/sd@"):
            import sdraw
            dummy, addr = path.split("@")
            addr = int(addr)
            sd_raw = sdraw.sdraw()
            result = sd_raw.sd_write_stream(data_client,addr)
            del sd_raw, addr, dummy
            data_client.close()
          else:
            self.save_file_data(path, data_client,
                                "w" if command == "STOR" else "a")
            result = True
          # if the next statement is reached,
          # the data_client was closed.
          data_client = None
        except:
          if data_client is not None:
            data_client.close()
        if result:
          cl.sendall("226 Done.\r\n")
        else:
          cl.sendall('550 Fail\r\n')
        del result
      elif command == "SIZE":
        try:
          cl.sendall('213 {}\r\n'.format(uos.stat(path)[6]))
        except:
          cl.sendall('550 Fail\r\n')
      elif command == "STAT":
        if payload == "":
          cl.sendall("211-Connected to ({})\r\n"
                     "    Data address ({})\r\n"
                     "    TYPE: Binary STRU: File MODE: Stream\r\n"
                     "    Session timeout {}\r\n"
                     "211 Client count is {}\r\n".format(
                      self.remote_addr, self.pasv_data_addr,
                      _COMMAND_TIMEOUT, len(client_list)))
        else:
          cl.sendall("213-Directory listing:\r\n")
          self.send_list_data(path, cl, True)
          cl.sendall("213 Done.\r\n")
      elif command == "DELE":
        try:
          uos.remove(path)
          cl.sendall('250 OK\r\n')
        except:
          cl.sendall('550 Fail\r\n')
      elif command == "RNFR":
        try:
          # just test if the name exists, exception if not
          uos.stat(path)
          self.fromname = path
          cl.sendall("350 Rename from\r\n")
        except:
          cl.sendall('550 Fail\r\n')
      elif command == "RNTO":
        try:
          uos.rename(self.fromname, path)
          cl.sendall('250 OK\r\n')
        except:
          cl.sendall('550 Fail\r\n')
        self.fromname = None
      elif command == "CDUP" or command == "XCUP":
        self.cwd = self.get_absolute_path(self.cwd, "..")
        cl.sendall('250 OK\r\n')
      elif command == "RMD" or command == "XRMD":
        try:
          uos.rmdir(path)
          cl.sendall('250 OK\r\n')
        except:
          cl.sendall('550 Fail\r\n')
      elif command == "MKD" or command == "XMKD":
        try:
          uos.mkdir(path)
          cl.sendall('250 OK\r\n')
        except:
          cl.sendall('550 Fail\r\n')
      elif command == "SITE":
        if path == "/mount":
          if self.mount():
            cl.sendall('250 OK\r\n')
          else:
            cl.sendall('550 Fail\r\n')
        elif path == "/umount":
          if self.umount():
            cl.sendall('250 OK\r\n')
          else:
            cl.sendall('550 Fail\r\n')
        elif path == "/passthru":
          import ecp5
          ecp5.passthru()
          cl.sendall('250 OK passthru\r\n')
        elif path.endswith(".bit") or path.endswith(".bit.gz"):
          try:
            import ecp5
            if ecp5.prog(path, close=False):
              if path.startswith("/sd/"):
                try:
                  self.umount()
                  cl.sendall('111 umount /sd OK\r\n')
                except:
                  cl.sendall('411 umount /sd Fail\r\n')
              if ecp5.prog_close():
                cl.sendall('250 OK\r\n')
              else:
                cl.sendall('550 Fail\r\n')
            else:
              cl.sendall('550 Fail\r\n')
          except:
            cl.sendall('550 Fail\r\n')
        else:
          if path.startswith("/"):
            exe=path[1:]
          else:
            exe=path
          try:
            exec(exe)
            cl.sendall('250 OK '+exe+'\r\n')
          except:
            cl.sendall('550 Fail '+exe+'\r\n')
          del exe
      else:
        cl.sendall("502 Unsupported command.\r\n")
        # log_msg(2,
        #  "Unsupported command {} with payload {}".format(command,
        #  payload))
    # handle unexpected errors
    except Exception as err:
      log_msg(1, "Exception in exec_ftp_command: {}".format(err))
    # tidy up before leaving
    client_busy = False
Esempio n. 30
0
if TTGO:
    pass
else:  #windows
    curdir = os.curdir
    print(curdir)  # '.'

# ziel bereitstellen ( in ttgo sd card via spi verbinden)
# bei ttgo sd mount sd card

if TTGO:
    from machine import SDCard
    filesystem = SDCard(slot=2,
                        width=1,
                        cd=None,
                        wp=None,
                        sck=14,
                        miso=2,
                        mosi=15,
                        cs=13)
    os.mount(
        filesystem,
        '/sd')  #Will raise OSError(EPERM) if mount_point is already mounted.
    print("Filesystem check")
    print(os.listdir('/sd'))
else:  # windows
    # make zieldirectory, falls noch nicht vorhanden
    if os.path.isdir('./subdir'):
        pass
    else:
        os.mkdir("subdir")