def main():
    """Main function."""

    print("main_test(): start")

    micropython.alloc_emergency_exception_buf(100)

    ## Create the LCD instance.
    i2c = I2C(1, I2C.MASTER)
    lcd = I2cLcd(i2c, 0x27, 4, 20)

    ## Create the keypad instance.
    keypad = Keypad_uasyncio(queue_size=4, start=True)

    ## Get a handle to the asyncio event loop.
    loop = asyncio.get_event_loop()

    ## Add the keypad scanning and keypad watcher coroutines.
    loop.create_task(keypad.scan_coro())
    loop.create_task(keypad_lcd_task(lcd=lcd, keypad=keypad))

    ## Start running the coroutines
    loop.run_forever()

    print("main_test(): end")
示例#2
0
def start(port=21, verbose=0, splash=True):
    global ftpsockets, datasocket
    global verbose_l
    global client_list
    global client_busy

    alloc_emergency_exception_buf(100)
    verbose_l = verbose
    client_list = []
    client_busy = False

    for interface in [network.AP_IF, network.STA_IF]:
        wlan = network.WLAN(interface)
        if not wlan.active():
            continue

        ifconfig = wlan.ifconfig()
        addr = socket.getaddrinfo(ifconfig[0], port)
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        sock.bind(addr[0][4])
        sock.listen(1)
        sock.setsockopt(socket.SOL_SOCKET,
                        _SO_REGISTER_HANDLER,
                        lambda s : accept_ftp_connect(s, ifconfig[0]))
        ftpsockets.append(sock)
        if splash:
            print("FTP server started on {}:{}".format(ifconfig[0], port))

    datasocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    datasocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    datasocket.bind(('0.0.0.0', _DATA_PORT))
    datasocket.listen(1)
    datasocket.settimeout(10)
示例#3
0
def setup():
    global g_Watchdog
    global g_Blinker
    global g_User
    global g_Log
    global g_MQTT

    micropython.alloc_emergency_exception_buf(100)

    g_Watchdog = Watchdog()
    Watchdog.__init__ = None

    g_Blinker = Blinker(2, 100)
    Blinker.__init__ = None

    g_Log = Log.Log()
    Log.Log.__init__ = None

    l_Wifi = Wifi.Wifi(g_Log, g_Blinker)
    g_MQTT = MQTT(l_Wifi.f_AP)
    Wifi.Wifi = None  # init done, no longer needed. Saves almost 1 Kbytes!!!
    MQTT.__init__ = None

    try:
        g_User = User(g_MQTT)
        User.__init__ = None
    except Exception as l_Exception:
        g_User = None
        l_Message = trace2string(l_Exception)
        g_Log.add("Usr:", l_Message)
        print(l_Message)
示例#4
0
def test():
    """Test program - assumes X2 is jumpered to X1."""
    micropython.alloc_emergency_exception_buf(100)

    print("Starting tach")
    tach = Tachometer(timer_num=2, channel_num=1, pin_name='X1')

    print("Starting pulses")
    t5 = pyb.Timer(5, freq=4)
    oc_pin = pyb.Pin.board.X2
    oc = t5.channel(2, pyb.Timer.OC_TOGGLE, pin=oc_pin)

    for freq in range(0, 600, 100):
        if freq == 0:
            freq = 1
        else:
            t5.freq(freq * 4)   # x 2 for toggle, x2 for 2 pulses_per_rev
        pyb.delay(1000)
        print("RPM =",  tach.rpm(), "Freq =", freq, " as RPM =", freq * 60)

    # stop the pulses
    print("Stopping pulses")
    oc_pin.init(pyb.Pin.OUT_PP)
    # wait for 1.5 seconds
    pyb.delay(1500)
    print("RPM =",  tach.rpm())
    print("RPM =",  tach.rpm())

    print("Starting pulses again")
    # start the pulses up again
    oc = t5.channel(2, pyb.Timer.OC_TOGGLE, pin=oc_pin)
    pyb.delay(2000)
    print("RPM =",  tach.rpm())
    print("RPM =",  tach.rpm())
示例#5
0
 def __init__(self):
   self.screen_x = const(64)
   self.screen_y = const(20)
   self.cwd = "/"
   self.init_fb()
   self.exp_names = " KMGTE"
   self.mark = bytearray([32,16,42]) # space, right triangle, asterisk
   self.diskfile=False
   self.data_buf=bytearray(554)
   self.mdv_byte=bytearray(1)
   self.mdv_phase=bytearray([1])
   self.read_dir()
   self.spi_read_irq = bytearray([1,0xF1,0,0,0,0,0])
   self.spi_read_btn = bytearray([1,0xFB,0,0,0,0,0])
   self.spi_read_blktyp = bytearray([1,0xD0,0,0,0,0,0])
   self.spi_result = bytearray(7)
   self.spi_enable_osd = bytearray([0,0xFE,0,0,0,1])
   self.spi_write_osd = bytearray([0,0xFD,0,0,0])
   self.spi_send_mdv_bram = bytearray([0,0xD1,0,0,0])
   self.spi_channel = const(2)
   self.spi_freq = const(3000000)
   self.init_pinout_sd()
   self.init_spi()
   alloc_emergency_exception_buf(100)
   self.enable = bytearray(1)
   self.timer = Timer(3)
   self.irq_handler(0)
   self.irq_handler_ref = self.irq_handler # allocation happens here
   self.spi_request = Pin(0, Pin.IN, Pin.PULL_UP)
   self.spi_request.irq(trigger=Pin.IRQ_FALLING, handler=self.irq_handler_ref)
示例#6
0
 def __init__(self):
     self.screen_x = const(64)
     self.screen_y = const(20)
     self.cwd = "/"
     self.init_fb()
     self.exp_names = " KMGTE"
     self.mark = bytearray([32, 16, 42])  # space, right triangle, asterisk
     self.read_dir()
     self.spi_read_irq = bytearray([1, 0xF1, 0, 0, 0, 0, 0])
     self.spi_read_btn = bytearray([1, 0xFB, 0, 0, 0, 0, 0])
     self.spi_result = bytearray(7)
     self.spi_enable_osd = bytearray([0, 0xFE, 0, 0, 0, 1])
     self.spi_write_osd = bytearray([0, 0xFD, 0, 0, 0])
     self.spi_channel = const(2)
     self.spi_freq = const(3000000)
     self.init_pinout_sd()
     #self.spi=SPI(self.spi_channel, baudrate=self.spi_freq, polarity=0, phase=0, bits=8, firstbit=SPI.MSB, sck=Pin(self.gpio_sck), mosi=Pin(self.gpio_mosi), miso=Pin(self.gpio_miso))
     self.init_spi()
     alloc_emergency_exception_buf(100)
     self.enable = bytearray(1)
     self.timer = Timer(3)
     self.irq_handler(0)
     self.irq_handler_ref = self.irq_handler  # allocation happens here
     self.spi_request = Pin(0, Pin.IN, Pin.PULL_UP)
     self.spi_request.irq(trigger=Pin.IRQ_FALLING,
                          handler=self.irq_handler_ref)
示例#7
0
 def install(self):
     micropython.alloc_emergency_exception_buf(100)
     self.screen.running = True
     uos.dupterm(self)
     self.poller.init(period=10,
                      mode=Timer.ONE_SHOT,
                      callback=self.schedule_poll_ref)
示例#8
0
    def __init__(self, os_properties):
        # Read OS properties
        self.os_properties = os_properties
        micropython.alloc_emergency_exception_buf(100)

        # Logger
        self.logger = Logger(self.os_properties['log_level'])
示例#9
0
def main():
    micropython.alloc_emergency_exception_buf(100)
    print('simp here')
    beam = LaserBeam('X1', 'X11')
    deck = CL1('X17', 'X18', 'X19', 'X20', 'X21', 'X22')
    piano = Piano(beam)
    lights = Lights(beam, deck)
    pushbutton = Switch()
    verbose = False

    def show():
        lights.update()
        if not verbose:
            return
        print('{}: laser {}'.format(ticks_ms(), beam.interrupted()), end=' ')
        sleep(0.1)
        print('deck %s' % deck.status(), end=' ')
        if piano.playing():
            print('Piano being played', end='')
        print()

    sleep(1)                    # stabilize
    while True:
        show()
        if piano.playing() and not deck.recording():
            deck.record()
            print("record")
            while piano.playing():
                show()
            deck.stop()
            print("stop")
示例#10
0
def test():
    """Test program - assumes X2 is jumpered to X1."""
    micropython.alloc_emergency_exception_buf(100)

    print("Starting tach")
    tach = Tachometer(timer_num=2, channel_num=1, pin_name='X1')

    print("Starting pulses")
    t5 = pyb.Timer(5, freq=4)
    oc_pin = pyb.Pin.board.X2
    oc = t5.channel(2, pyb.Timer.OC_TOGGLE, pin=oc_pin)

    for freq in range(0, 600, 100):
        if freq == 0:
            freq = 1
        else:
            t5.freq(freq * 4)  # x 2 for toggle, x2 for 2 pulses_per_rev
        pyb.delay(1000)
        print("RPM =", tach.rpm(), "Freq =", freq, " as RPM =", freq * 60)

    # stop the pulses
    print("Stopping pulses")
    oc_pin.init(pyb.Pin.OUT_PP)
    # wait for 1.5 seconds
    pyb.delay(1500)
    print("RPM =", tach.rpm())
    print("RPM =", tach.rpm())

    print("Starting pulses again")
    # start the pulses up again
    oc = t5.channel(2, pyb.Timer.OC_TOGGLE, pin=oc_pin)
    pyb.delay(2000)
    print("RPM =", tach.rpm())
    print("RPM =", tach.rpm())
示例#11
0
    def main(self):
        """
        Main function where interrupt handler is initialized and a callback
        function passed
        
        :param: None
        :return: None
        """
        # Allocate exception buffer since heap cannot be allocated within an ISR context
        micropython.alloc_emergency_exception_buf(100)
        # Set up interrupt handler
        ext_int = pyb.ExtInt(self.pin, pyb.ExtInt.IRQ_FALLING,
                             pyb.Pin.PULL_NONE, self.measure)

        while self.num_seconds < (self.max_duration // self.sample_period):
            # Sleep for specified interval to count number of interrupts received
            time.sleep(self.sample_period)
            # Disable IRQs and process result
            pyb.disable_irq()
            rpm = self.irq_count * 60 / (2 * self.blades)
            output_str = str(self.num_seconds) + "," + "{0:.2f}".format(rpm)
            # Print the result to serial console
            print(output_str)
            # Reset IRQ counter for the next interval
            self.irq_count = 0
            self.num_seconds += self.sample_period
            # Enable IRQs
            pyb.enable_irq()
示例#12
0
def main():
    micropython.alloc_emergency_exception_buf(100)
    print('simp here')
    beam = LaserBeam('X1', 'X11')
    deck = CL1('X17', 'X18', 'X19', 'X20', 'X21', 'X22')
    piano = Piano(beam)
    lights = Lights(beam, deck)
    pushbutton = Switch()
    verbose = False

    def show():
        lights.update()
        if not verbose:
            return
        print('{}: laser {}'.format(ticks_ms(), beam.interrupted()), end=' ')
        sleep(0.1)
        print('deck %s' % deck.status(), end=' ')
        if piano.playing():
            print('Piano being played', end='')
        print()

    sleep(1)  # stabilize
    while True:
        show()
        if piano.playing() and not deck.recording():
            deck.record()
            print("record")
            while piano.playing():
                show()
            deck.stop()
            print("stop")
示例#13
0
    def __init__(self, pin, timer, channel):
        ''' Initializes the infared receiver
        @param pin: pin is a pyb.Pin.board object
            for the interrupt pin that will detect interrupts
            from the IR reciever
        @param timer: timer is the timer the interrupt pin will use
        @param channel: channel is the channel the timer will use
        '''
        #----------------------------------------------------------------------#
        # Allocate memory so that exceptions raised in interrupt service
        # routines can generate useful diagnostic printouts
        # comment this line out after testing
        alloc_emergency_exception_buf(100)
        #----------------------------------------------------------------------#

        # assign the pin as an input pin
        intPin = pyb.Pin(pin, pyb.Pin.IN)

        # channel is the channel the timer will use, specified by the function
        # parameter. Has to be brought to the Class scope because it is used in
        # the irISR callback function
        self.channel = channel
        # Assign the timer a 16-bit period and a prescaler of 79 to collect
        # accurate timestamps. Prescaler of 79 to account for 80Mhz clock speed
        # to output counts as microseconds
        tim = pyb.Timer(timer, prescaler=79, period=0xFFFF)

        # set up the timer object to detect rising and fallingedges
        tim.channel(channel,
                    pyb.Timer.IC,
                    polarity=pyb.Timer.BOTH,
                    pin=intPin,
                    callback=self.irISR)

        # A queue to be used as a buffer for interrupt timestamp data. Buffer
        # size is greater than full pulse count to account for repeat codes
        # that disrupt a full pulse set.
        self.ir_data = task_share.Queue('I',
                                        200,
                                        thread_protect=False,
                                        overwrite=False,
                                        name="ir_data")
        # Data is a class scoped list that is filled with timestamps
        # from the ir_data queue
        self.data = []

        self.address = task_share.Share('I',
                                        thread_protect=False,
                                        name="address")
        self.command = task_share.Share('I',
                                        thread_protect=False,
                                        name="address")
        self.command.put(0)
        self.address.put(0)
        self.task = cotask.Task(self.readInfaredSensorTask,
                                name='Infared Reading Task',
                                priority=5,
                                profile=True,
                                trace=False)
示例#14
0
def emergency_mbuff():
    emergency_buff_kb = 1000
    if cfgget('extirq') or cfgget("timirq"):
        from micropython import alloc_emergency_exception_buf
        console_write("[IRQ] Interrupts was enabled, alloc_emergency_exception_buf={}".format(emergency_buff_kb))
        alloc_emergency_exception_buf(emergency_buff_kb)
    else:
        console_write("[IRQ] Interrupts disabled, skip alloc_emergency_exception_buf configuration.")
示例#15
0
def init():
    if False:
        uart = pyb.UART(6,115200)
        pyb.repl_uart(uart)
        print("REPL is also on UART 6 (Y1=Tx Y2=Rx)")
    if True:
        bufsize = 100
        print("Setting alloc_emergency_exception_buf to",  bufsize)
        micropython.alloc_emergency_exception_buf(bufsize)
示例#16
0
 def __repr__(self):
     # See:
     micropython.alloc_emergency_exception_buf(100)
     objState.strState = STATE_RUNNING
     objState.listErrorMessages = []
     timer1.init(freq=0.5)  # 0.5 Hz
     timer1.callback(
         lambda objTimer: micropython.schedule(schedule_timer1, 4712))
     button1.callback(lambda: micropython.schedule(schedule_button, 4712))
     return ''
示例#17
0
    def demo():
        # This example requires a servo on X1 and a signal (from a radio) on X4.
        micropython.alloc_emergency_exception_buf(100)

        in_ppm = Ppm(pyb.Pin.board.X4, pyb.Servo(1))

        while True:
            # wait forever
            pyb.delay(200)
            print("%d%% %d deg %d speed (%s) %d us" % (in_ppm.percent(), in_ppm.angle(), in_ppm.speed(), "True" if in_ppm.switch() else "False", in_ppm.pulse_width))
示例#18
0
    def demo():
        # This example requires a servo on X1 and a signal (CPPM from a radio) on X4.
        micropython.alloc_emergency_exception_buf(100)

        in_cppm = Cppm(pyb.Pin.board.X4, 8, pyb.Servo(1))

        while True:
            # wait forever
            pyb.delay(200)
            for i, ch in enumerate(in_cppm.ch):
                print("Channel %d: %d%% %d deg %d speed (%s) %d us %s" % (i, ch.percent(), ch.angle(), ch.speed(), "True" if ch.switch() else "False", ch.pulse_width, str(ch.calibration())))
示例#19
0
文件: cppm.py 项目: rizzak/esp_bb
    def demo():
        # This example requires a servo on X1 and a signal (from a radio) on X4.
        micropython.alloc_emergency_exception_buf(100)

        in_ppm = Ppm(pyb.Pin(3))

        while True:
            # wait forever
            pyb.delay(200)
            print("%d%% %d deg %d speed (%s) %d us" %
                  (in_ppm.percent(), in_ppm.angle(), in_ppm.speed(),
                   "True" if in_ppm.switch() else "False", in_ppm.pulse_width))
示例#20
0
 def __init__(self, pin, mode, pull, customcallback = None, timeout = None):
     super().__init__()
     if not Pinblock.initialised:
         import pyb
         import micropython
         micropython.alloc_emergency_exception_buf(100) 
         Pinblock.initialised = True
     self.customcallback = customcallback
     if timeout is None:
         self.forever = True
     else:
         self.setdelay(timeout)
     self.irq = pyb.ExtInt(pin, mode, pull, self.intcallback) # Porting: needs adaptation
示例#21
0
 def collect(self):
     """
     Set up Timer interrupt that fires every 10 seconds. Clock used for this
     in the Micropython board is 84MHz. Prescaler of 83 + 1 sclaes this 
     frequency to 1MHz. Finally, a period of 9999999 + 1 = 10000000 equates to
     10 seconds. Call back function is specified in the timer instance.
     """
     header = "Time, Elapsed(s), TMP36(F), SHT31D(F)"
     self.serial.write(header)
     print(header)
     self.timer = pyb.Timer(2, prescaler=83, period=9999999)
     micropython.alloc_emergency_exception_buf(100)
     self.timer.callback(self.schedule)
示例#22
0
文件: cppm.py 项目: rizzak/esp_bb
    def demo():
        # This example requires a servo on X1 and a signal (CPPM from a radio) on X4.
        micropython.alloc_emergency_exception_buf(100)

        in_cppm = Cppm(pyb.Pin(3), 8)

        while True:
            # wait forever
            time.sleep_ms(200)
            for i, ch in enumerate(in_cppm.ch):
                print("Channel %d: %d%% %d deg %d speed (%s) %d us %s" %
                      (i, ch.percent(), ch.angle(), ch.speed(),
                       "True" if ch.switch() else "False", ch.pulse_width,
                       str(ch.calibration())))
示例#23
0
def servo_service():
    micropython.alloc_emergency_exception_buf(100)

    for i in range(0,4):
        for j in range(0,3):
            if (abs(site_now[i][j] - site_expect[i][j]) >= abs(temp_speed[i][j])):
                site_now[i][j] += temp_speed[i][j]
            else:
                site_now[i][j] = site_expect[i][j]

        cartesian_to_polar(alpha, beta, gamma, site_now[i][0], site_now[i][1], site_now[i][2])
        polar_to_servo(i, alpha, beta, gamma)

    rest_counter+=1
示例#24
0
def main():
    """
    Main entry point into this program
    
    :param: None
    :return: None
    """
    micropython.alloc_emergency_exception_buf(100)
    connect_wifi()
    oled.fill(0)
    oled.text("Waiting for data", 0, 29)
    oled.show()
    timer = Timer(-1)
    timer.init(mode=Timer.PERIODIC, period=INTERVAL_MS, callback=schedule)
示例#25
0
 def __init__(self, pin, mode, pull, customcallback=None, timeout=None):
     super().__init__()
     if not Pinblock.initialised:
         import pyb
         import micropython
         micropython.alloc_emergency_exception_buf(100)
         Pinblock.initialised = True
     self.customcallback = customcallback
     if timeout is None:
         self.forever = True
     else:
         self.setdelay(timeout)
     self.irq = pyb.ExtInt(pin, mode, pull,
                           self.intcallback)  # Porting: needs adaptation
示例#26
0
def main():
    '''
    After the startup this functions collects some data, depending
    on the state of the WLAN connection.
    '''
    gc.enable()
    micropython.alloc_emergency_exception_buf(5000)
    try:
        nic = network.WLAN(network.STA_IF)
        mqttCounter = 0
        eventTimer = time.time()
        wlanData, connectTime, ntpResult, ntpLastSuccess = startupSequenz(nic)
    except Exception as e:
        sys.print_exception(e)
        machine.reset()
        eventTimer = eventScheduler(ioEventTimer, )
    while True:
        try:
            printDebug("wlanData", wlanData)
            printDebug("connectTime", connectTime)
            printDebug("eventTimer", eventTimer)
            printDebug("mqttCounter", mqttCounter)
            if nic.isconnected():
                (
                    wlanData,
                    connectTime,
                    eventTimer,
                    mqttCounter,
                    ntpResult,
                    ntpLastSuccess,
                ) = connectedSchedule(
                    nic,
                    wlanData,
                    connectTime,
                    eventTimer,
                    mqttCounter,
                    ntpResult,
                    ntpLastSuccess,
                )
            else:
                (wlanData, connectTime, eventTimer) = disconnectedSchedule(
                    nic,
                    wlanData,
                    connectTime,
                    eventTimer,
                )
            gc.collect()
        except Exception as e:
            sys.print_exception(e)
            machine.reset()
示例#27
0
def set_emergency_buffer():
    from micropython import alloc_emergency_exception_buf
    irqmembuf = cfgget('irqmembuf')
    emergency_buff_kb = irqmembuf if irqmembuf is not None and isinstance(
        irqmembuf, int) else 1000
    if cfgget('extirq') or cfgget("timirq"):
        console_write(
            "[IRQ] Interrupts was enabled, alloc_emergency_exception_buf={}".
            format(emergency_buff_kb))
        alloc_emergency_exception_buf(emergency_buff_kb)
    else:
        console_write(
            "[IRQ] Interrupts disabled, skip alloc_emergency_exception_buf configuration."
        )
示例#28
0
def test():
    global keypadTimerFreq
    from Keypad import *
    print("test(): start")

    micropython.alloc_emergency_exception_buf(100)
    keys = [
        '1',
        '2',
        '3',
        'A',
        '4',
        '5',
        '6',
        'B',
        '*',
        '0',
        '#',
        'D',
        '7',
        '8',
        '9',
        'C',
    ]

    longkeys = {
        12: '\bHello, ',
        13: '\bWorld',
    }

    keypad = Keypad(['PE10', 'PE9', 'PE8', 'PE7'], \
            ['PE14', 'PE13', 'PE12', 'PE11'], {12, 13}, \
            5, keypadTimerFreq)
    hstry = None
    try:
        #for i in range(10000):
        while True:
            key = keypad.get_key()
            if key != None:
                if key >= 100:
                    key = longkeys[key - 100]
                else:
                    key = keys[key]
                print(key, end='')
                if hstry == '*' and key == '*':
                    break
                hstry = key
            delay(1)
    except Exception as ex:
        pass
示例#29
0
def start(port=21, verbose=0, splash=True):
    global ftpsocket, datasocket
    global verbose_l
    global client_list
    global client_busy
    global AP_addr, STA_addr

    alloc_emergency_exception_buf(100)
    verbose_l = verbose
    client_list = []
    client_busy = False

    ftpsocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    datasocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

    ftpsocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    datasocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

    ftpsocket.bind(('0.0.0.0', port))
    datasocket.bind(('0.0.0.0', _DATA_PORT))

    ftpsocket.listen(0)
    datasocket.listen(0)

    datasocket.settimeout(10)
    ftpsocket.setsockopt(socket.SOL_SOCKET, _SO_REGISTER_HANDLER,
                         accept_ftp_connect)

    wlan = network.WLAN(network.AP_IF)
    if wlan.active():
        ifconfig = wlan.ifconfig()
        # save IP address string and numerical values of IP adress and netmask
        AP_addr = (ifconfig[0], num_ip(ifconfig[0]), num_ip(ifconfig[1]))
        if splash:
            print("FTP server started on {}:{}".format(ifconfig[0], port))
    wlan = network.WLAN(network.STA_IF)
    if wlan.active():
        ifconfig = wlan.ifconfig()
        # save IP address string and numerical values of IP adress and netmask
        STA_addr = (ifconfig[0], num_ip(ifconfig[0]), num_ip(ifconfig[1]))
        if splash:
            print("FTP server started on {}:{}".format(ifconfig[0], port))
    wlan = network.LAN()
    if wlan.active():
        ifconfig = wlan.ifconfig()
        # save IP address string and numerical values of IP adress and netmask
        STA_addr = (ifconfig[0], num_ip(ifconfig[0]), num_ip(ifconfig[1]))
        if splash:
            print("FTP server started on {}:{}".format(ifconfig[0], port))
示例#30
0
文件: osd.py 项目: emard/ulx3s_mac128
 def __init__(self):
     self.screen_x = const(64)
     self.screen_y = const(20)
     self.cwd = "/"
     self.init_fb()
     self.exp_names = " KMGTE"
     self.mark = bytearray([32, 16, 42])  # space, right triangle, asterisk
     self.diskfile = [open("main.py", "rb"),
                      open("main.py", "rb")]  # any dummy file that can open
     self.imgtype = bytearray(
         2)  # [0]=0:.mac/.bin 1638400 bytes, [0]=1:.dsk 819200 bytes
     self.drive = bytearray(1)  # [0]=0:1st drive, [0]=1:2nd drive
     self.conv_dataIn12K = bytearray(12 * 1024)
     # memoryview for each track//16
     datainmv = memoryview(self.conv_dataIn12K)
     self.conv_dataIn = []
     for i in range(5):
         self.conv_dataIn.append(memoryview(datainmv[0:(12 - i) * 1024]))
     self.conv_nibsOut = bytearray(1024)
     dsk2mac.init_nibsOut(self.conv_nibsOut)
     self.track2sector = bytearray(81 * 2)
     self.init_track2sector()
     self.read_dir()
     self.spi_read_irq = bytearray([1, 0xF1, 0, 0, 0, 0, 0])
     self.spi_read_btn = bytearray([1, 0xFB, 0, 0, 0, 0, 0])
     self.spi_read_trackno = bytearray([1, 0xD0, 0, 0, 0, 0, 0])
     self.spi_result = bytearray(7)
     self.spi_enable_osd = bytearray([0, 0xFE, 0, 0, 0, 1])
     self.spi_write_osd = bytearray([0, 0xFD, 0, 0, 0])
     self.spi_write_track = [
         bytearray([0, 0xD1, 0, 0, 0]),
         bytearray([0, 0xD1, 0, 0x60, 0])
     ]
     self.spi_channel = const(2)
     self.spi_freq = const(3000000)
     self.init_pinout_sd()
     self.init_spi()
     alloc_emergency_exception_buf(100)
     self.enable = bytearray(1)
     self.timer = Timer(3)
     self.irq_handler(0)
     self.irq_handler_ref = self.irq_handler  # allocation happens here
     self.spi_request = Pin(0, Pin.IN, Pin.PULL_UP)
     self.spi_request.irq(trigger=Pin.IRQ_FALLING,
                          handler=self.irq_handler_ref)
示例#31
0
文件: ps2tn.py 项目: emard/apple2fpga
 def __init__(self, ps2socket):
     self.command_client, self.remote_addr = ps2socket.accept()
     self.command_client.setblocking(False)
     self.command_client.sendall(bytes([255, 252,
                                        34]))  # dont allow line mode
     self.command_client.sendall(bytes([255, 251,
                                        1]))  # turn off local echo
     self.command_client.recv(32)  # drain junk
     sleep_ms(20)
     self.command_client.recv(32)  # drain junk
     self.remote_addr = self.remote_addr[0]
     #self.command_client.settimeout(_COMMAND_TIMEOUT)
     log_msg(1, "PS2 Command connection from:", self.remote_addr)
     self.command_client.setsockopt(socket.SOL_SOCKET, _SO_REGISTER_HANDLER,
                                    self.exec_ps2_command)
     self.act_data_addr = self.remote_addr
     self.active = True
     alloc_emergency_exception_buf(100)
示例#32
0
文件: ps2tn.py 项目: emard/esp32ps2
def start(port=23, verbose=0, splash=True):
    global ps2socket
    global verbose_l
    global client_list
    global client_busy
    global ps2port

    alloc_emergency_exception_buf(100)
    verbose_l = verbose
    client_list = []
    client_busy = False

    ps2socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    ps2socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    ps2socket.bind(('0.0.0.0', port))
    ps2socket.listen(0)
    ps2socket.setsockopt(socket.SOL_SOCKET, _SO_REGISTER_HANDLER,
                         accept_ps2_connect)
def main():
    import statusled
    import configuration
    print("Testing Connection...")

    micropython.alloc_emergency_exception_buf(100)

    config = configuration.Configuration()

    led = statusled.StatusLED()
    led.start()

    conn = Connection(config, status_led=led)
    conn.start()

    loop = asyncio.get_event_loop()
    loop.create_task(led.blink_lights())
    loop.create_task(conn.stay_connected())
    loop.run_forever()
示例#34
0
def main():
    # Some ports requires to allocate extra mem for exceptions
    if hasattr(micropython, 'alloc_emergency_exception_buf'):
        micropython.alloc_emergency_exception_buf(100)

    # Main loop
    try:
        loop = asyncio.get_event_loop()
        app = App(loop)
        app.run()
        loop.run_forever()
    except KeyboardInterrupt as e:
        pass
    except Exception as e:
        log = logging.Logger('main')
        log.exc(e, "Unhandled exception in main loop")

    # Gracefully stop app
    app.stop()
    loop.run_until_complete(shutdown_wait())
示例#35
0
def main_test():
    import statusled

    print("Testing keypad...")

    micropython.alloc_emergency_exception_buf(100)

    led = statusled.StatusLED()
    led.start()

    kpd = Keypad(layout=TEL_16_KEY, status_led=led)
    kpd.start()

    loop = asyncio.get_event_loop()

    loop.create_task(kpd.scan_keypad())
    loop.create_task(keypad_watcher(keypad=kpd))
    loop.create_task(led.blink_lights())

    loop.run_forever()
示例#36
0
    def __init__(self):
        #com1 = pyb.USB_VCP()  # A Virtual COM port
        self.mpu = MPU9250('y')
        self.mpu.sample_rate = 254
        self.mpu.accel_filter_range = 5
        self.mpu.gyro_filter_range = 2
        self.led1 = pyb.LED(1)
        self.led2 = pyb.LED(2)
        self.led3 = pyb.LED(3)
        self.led4 = pyb.LED(4)
        self.led3.on()
        self.kalmanX = kalmanFilter()
        self.led4.on()
        self.timeX = pyb.micros()
        self.kalmanY = kalmanFilter()
        self.timeY = pyb.micros()
        self.kalmanZ = kalmanFilter()
        self.timeZ =  pyb.micros()
        micropython.alloc_emergency_exception_buf(5)
        self.led4.on()


        self.display = NextionUartDriver.NextionDisplay(1,115200)
示例#37
0
import pyb, micropython, array, uctypes
micropython.alloc_emergency_exception_buf(100)

class MutexException(OSError):
    pass

class Mutex:
    @micropython.asm_thumb
    def _acquire(r0, r1):       # Spinlock: wait on the semaphore. Return on success.
        label(LOOP)
        ldr(r0, [r1, 0])        # Wait for lock to be zero
        cmp(r0, 0)
        bne(LOOP)               # Another process has the lock: spin on it
        cpsid(0)                # OK, we have lock  at this instant disable interrupts
        ldr(r0, [r1, 0])        # and re-check in case an interrupt occurred
        cmp(r0, 0)
        itt(ne)                 # if someone got in first re-enable ints
        cpsie(0)                # and start polling again
        b(LOOP)
        mov(r0, 1)              # We have an exclusive access
        str(r0, [r1, 0])        # set the lock
        cpsie(0)

    @micropython.asm_thumb
    def _attempt(r0, r1):       # Nonblocking. Try to lock. Return 0 on success, 1 on fail
        cpsid(0)                # disable interrupts
        ldr(r0, [r1, 0])
        cmp(r0, 0)
        bne(FAIL)               # Another process has the lock: fail
        mov(r2, 1)              # No lock
        str(r2, [r1, 0])        # set the lock
示例#38
0
import time
import machine
import micropython
from machine import Pin
# HC-SR04 ultrasonic sensor
# 2 pins: Trigger and Echo
# Trigger triggers the wave to get the distance
# Echo listen to the wave 'comeback'
# To trigger: send during 10us a HIGH signal on the Trigger
# Then, on echo, the signal is HIGH while listening to the wave comeback
# Formulae to calculate: t * 10^-2 * 1,7

micropython.alloc_emergency_exception_buf(100)	# To allow error trace in IRQ handler
	
MIN_TO_SEC = 60			# Number of sec in 1 min
SEC_TO_USEC = 1000		# Number of msec in 1 sec

TRIGGER_TIME = 100 		# Trigger time during which send the HIGH signal
TRIGGER_PIN = 'GP11'	# Pin associated to the trigger 
ECHO_PIN = 'GP12'		# Pin associated to the echo

LOW = 0
HIGH = 1

class DistanceSensor:
	def __init__(self, triggerGPIO, echoGPIO):
		self.triggerPin = Pin(triggerGPIO, mode = Pin.OUT)
		self.echoPin = Pin(echoGPIO, mode = Pin.IN)
		# The var to know if we have 28 or 028 in the decimal part
		self.mm_decimal = ""
		# Distance initated to -1 while nothing
示例#39
0
def main():
    micropython.alloc_emergency_exception_buf(100)
    print('simp here')
    beam = LaserBeam('X1', 'X11')
    mic = Mic('X12')
    deck = CL1('X17', 'X18', 'X19', 'X20', 'X21', 'X22')
    piano = Piano(mic, beam)
    lights = Lights(mic, beam, deck)
    pushbutton = Switch()
    verbose = False

    def was_show(): # BAD
        lights.update()
        #if pushbutton():
        if True:
            print('laser {}, mic {}'.format(beam.interrupted(), mic.excited()), end=' ')
            print('deck %s' % deck.status(), end=' ')
            if piano.playing():
                print('Piano being played', end='')
            print()

    def show():
        lights.update()
        print('laser {}'.format(beam.interrupted()), end=' ')
        print('deck %s' % deck.status(), end=' ')
        if piano.playing():
            print('Piano being played', end='')
        print()

    def s11(): # BAD
        mic.excited()
        print('deck %s' % deck.status())

    def s12(): # ok
        mic.excited()
        sleep(0.1)
        print('deck %s' % deck.status())

    def s13(): # BAD
        mic.excited()
        sleep(0.001)
        print('deck %s' % deck.status())

    def s14(): # BAD: prints "deck" (or maybe "deck ") only
        mic.excited()
        sleep(0.01)
        print('deck %s' % deck.status())

    def s15(): # BAD
        mic.excited()
        gc.collect()
        print('deck %s' % deck.status())

    def foo(): # ok
        print('deck %s' % deck.status(), end=' ')

    sleep(1)                    # stabilize
    while True:
        show()
        if piano.playing() and not deck.recording():
            deck.record()
            print("record")
            while piano.playing():
                show()
            deck.stop()
            print("stop")