예제 #1
0
파일: __init__.py 프로젝트: laczbali/kyanit
 def action_state(method, loc, params, headers, conn, addr):
     return httpsrv.response(
         200,
         ujson.dumps(
             {
                 "unique_id": ubinascii.hexlify(
                     machine.unique_id()
                 ).decode().upper(),
                 "micropython_version": uos.uname().version[
                     1:uos.uname().version.index(" ")
                 ],
                 "firmware_version": __version__,
                 "color_id": _color_id,
                 "free_memory": gc.mem_free(),
                 "free_flash": uos.statvfs("/")[0] * uos.statvfs("/")[3],
                 "run_state": [
                     "ERROR {}".format(runner.get_error()[0])
                     if runner.get_error() is not None
                     else "",
                     "STOPPED",
                     "CODE.PY MISSING",
                     "CODE.PY IMPORTED",
                     "CODE.PY MAIN",
                 ][runner.get_state()],
                 "error_traceback": [
                     line.strip()
                     for line in runner.get_error()[1].split("\n")
                     if line and "Traceback" not in line
                 ]
                 if runner.get_error() is not None
                 else None,  # noqa
             }
         ),
         httpsrv.CT_JSON,
     )
 def __init__(A, path=C, firmware_id=C):
     G = firmware_id
     C = path
     try:
         if os.uname(
         ).release == '1.13.0' and os.uname().version < 'v1.13-103':
             raise V('MicroPython 1.13.0 cannot be stubbed')
     except F:
         pass
     A._report = []
     A.info = _info()
     E.collect()
     if G: A._fwid = str(G).lower()
     else: A._fwid = '{family}-{ver}-{port}'.format(**A.info).lower()
     A._start_free = E.mem_free()
     if C:
         if C.endswith(B): C = C[:-1]
     else: C = get_root()
     A.path = '{}/stubs/{}'.format(C, A.flat_fwid).replace('//', B)
     try:
         T(C + B)
     except D:
         pass
     A.problematic = [
         'upip', 'upysh', 'webrepl_setup', 'http_client', 'http_client_ssl',
         'http_server', 'http_server_ssl'
     ]
     A.excluded = [
         'webrepl', '_webrepl', 'port_diag', 'example_sub_led.py',
         'example_pub_button.py'
     ]
     A.modules = []
예제 #3
0
    def Status(self, data=None):
        self.destroy()
        self.create_window()
        w = self.window
        y = 10
        gap = 5
        height = 35
        ugfx.Label(10, y, w.width() - 20, height, 'Platform: {}'.format(util.get_version()), parent=w)
        y += gap + height
        ugfx.Label(10, y, w.width() - 20, height, 'Release: {}'.format(uos.uname()[2]), parent=w)
        y += gap + height
        ugfx.Label(10, y, w.width() - 20, height, 'firmware:', parent=w)
        ugfx.set_default_font('IBMPlexMono_Bold18')
        y += height
        ugfx.Label(10, y, w.width() - 20, height + 10, '{}'.format(uos.uname()[3]), parent=w)
        ugfx.set_default_font(self.default_font)
        ugfx.set_default_font('IBMPlexSans_Regular18')
        self.create_status_box()
        ugfx.set_default_font(self.default_font)

        try:
            ota_data = ota.check_version()
        except ota.OtaException as e:
            self.set_status('Error: {}'.format(e))
        else:
            if ota_data:
                self.status_box.destroy()
                ugfx.Label(10, 180, 200, 40, text='New: {}'.format(ota_data['version']),
                    parent=w)
                self.btngroup = ButtonGroup(self.window, 190, 180, 110, 40, 10)
                self.btngroup.add('Upgrade', self.install_ota, ota_data)
                self.btngroup.end()
            else:
                self.set_status('Up to date')
def main():

    gc.collect()  # Loop runs device out of memory without this
    # Uncomment to monitor RAM usage
    #print('Free Memory: %sKB' % int(gc.mem_free()/1024)) 

    # Read the eTape Sensor
    water = Milone_eTape.inches()
    #print('Inches of Water: %.01f' % water)

    # Send the Data to Server
    data = "%s,device=%s inches=%.01f" % (measurement, client_id, water)
    print(data)
    response = urequests.post(url,headers=headers,data=data)
    #print('STATUS:', response.status_code)
    if '204' in str(response.status_code):  # HTTP Status 204 (No Content) indicates server successfull fulfilled request with no response content
        print('InfluxDB write: Success')
        print()
        if 'TinyPICO' in uname().machine:
            led.blink(0,255,0,ms=1500,i=1) # Green
    else:
        print('InfluxDB write: Failed')
        if 'TinyPICO' in uname().machine:
            led.solid(255,127,0)  # Orange
        sleep(sleep_interval)
        reset()
예제 #5
0
 def __init__(self, path: str = None, firmware_id: str = None):
     try:
         if os.uname(
         ).release == '1.13.0' and os.uname().version < 'v1.13-103':
             raise NotImplementedError(
                 "MicroPython 1.13.0 cannot be stubbed")
     except AttributeError:
         pass
     self._report = []
     self.info = self._info()
     if firmware_id:
         self._fwid = str(firmware_id).lower()
     else:
         self._fwid = "{family}-{port}-{ver}".format(**self.info).lower()
     self._start_free = gc.mem_free()
     if path:
         if path.endswith('/'):
             path = path[:-1]
     else:
         path = self.get_root()
     self.path = "{}/stubs/{}".format(path,
                                      self.flat_fwid).replace('//', '/')
     try:
         self.ensure_folder(path + "/")
     except OSError:
         pass
     self.problematic = [
         "upysh", "webrepl_setup", "http_client", "http_client_ssl",
         "http_server", "http_server_ssl"
     ]
     self.excluded = [
         "webrepl", "_webrepl", "port_diag", "example_sub_led.py",
         "example_pub_button.py"
     ]
     self.modules = [
         '_onewire', '_thread', '_uasyncio', 'ak8963', 'apa102', 'apa106',
         'array', 'binascii', 'btree', 'builtins', 'cmath', 'collections',
         'crypto', 'curl', 'dht', 'display', 'ds18x20', 'errno', 'esp',
         'esp32', 'flashbdev', 'framebuf', 'freesans20', 'functools', 'gc',
         'gsm', 'hashlib', 'heapq', 'inisetup', 'io', 'json', 'lcd160cr',
         'lcd160cr_test', 'logging', 'lwip', 'machine', 'math',
         'microWebSocket', 'microWebSrv', 'microWebTemplate', 'micropython',
         'mpu6500', 'mpu9250', 'neopixel', 'network', 'ntptime', 'onewire',
         'os', 'pyb', 'pycom', 'pye', 'queue', 'random', 're', 'requests',
         'select', 'socket', 'ssd1306', 'ssh', 'ssl', 'stm', 'struct',
         'sys', 'time', 'tpcalib', 'uarray', 'uasyncio/__init__',
         'uasyncio/core', 'uasyncio/event', 'uasyncio/funcs',
         'uasyncio/lock', 'uasyncio/stream', 'ubinascii', 'ubluetooth',
         'ucollections', 'ucrypto', 'ucryptolib', 'uctypes', 'uerrno',
         'uhashlib', 'uheapq', 'uio', 'ujson', 'ulab', 'ulab/approx',
         'ulab/compare', 'ulab/fft', 'ulab/filter', 'ulab/linalg',
         'ulab/numerical', 'ulab/poly', 'ulab/user', 'ulab/vector',
         'umachine', 'umqtt/robust', 'umqtt/simple', 'uos', 'upip',
         'upip_utarfile', 'uqueue', 'urandom', 'ure', 'urequests',
         'urllib/urequest', 'uselect', 'usocket', 'ussl', 'ustruct', 'usys',
         'utime', 'utimeq', 'uwebsocket', 'uzlib', 'websocket',
         'websocket_helper', 'writer', 'ymodem', 'zlib'
     ]
     self.include_nested = gc.mem_free() > 3200
예제 #6
0
    def __init__(self, path: str = None, firmware_id: str = None):
        try:
            if os.uname(
            ).release == "1.13.0" and os.uname().version < "v1.13-103":
                raise NotImplementedError(
                    "MicroPython 1.13.0 cannot be stubbed")
        except AttributeError:
            pass

        self._log = logging.getLogger("stubber")
        self._report = []
        self.info = _info()
        gc.collect()
        if firmware_id:
            self._fwid = str(firmware_id).lower()
        else:
            self._fwid = "{family}-{ver}-{port}".format(**self.info).lower()
        self._start_free = gc.mem_free()  # type: ignore

        if path:
            if path.endswith("/"):
                path = path[:-1]
        else:
            path = get_root()

        self.path = "{}/stubs/{}".format(path,
                                         self.flat_fwid).replace("//", "/")
        self._log.debug(self.path)
        try:
            ensure_folder(path + "/")
        except OSError:
            self._log.error("error creating stub folder {}".format(path))
        self.problematic = [
            "upip",
            "upysh",
            "webrepl_setup",
            "http_client",
            "http_client_ssl",
            "http_server",
            "http_server_ssl",
        ]
        self.excluded = [
            "webrepl",
            "_webrepl",
            "port_diag",
            "example_sub_led.py",
            "example_pub_button.py",
        ]
        # there is no option to discover modules from micropython, list is read from an external file.
        self.modules = []
예제 #7
0
def do_acess_point():
    global ap_if
    if uname().machine == 'ESP32 module with ESP32':  # Wemos ESP-WROOM-32
        import network
        ap_if = network.WLAN(network.AP_IF)
        ap_if.active(True)
        ap_if.config(essid=access_point_name, authmode=network.AUTH_OPEN)
    elif uname().machine == 'WiPy with ESP32':  # Wipy 2.0
        import pycom
        from network import WLAN
        pycom.heartbeat(False)
        ap_if = WLAN(mode=WLAN.AP, ssid=access_point_name)
    ap_if.ifconfig(
        ('192.168.4.1', '255.255.255.0', '192.168.4.1', '192.168.4.1'))
예제 #8
0
def get_fram():
    if uos.uname().machine.split(' ')[0][:4] == 'PYBD':
        Pin.board.EN_3V3.value(1)
        time.sleep(0.1)  # Allow decouplers to charge
    fram = FRAM(I2C(2))
    print('Instantiated FRAM')
    return fram
예제 #9
0
    def __init__(self, ledNumber=1, brightness=100, dataPin='P11'):
        """
        Params:
        * ledNumber = count of LEDs
        * brightness = light brightness (integer : 0 to 100%)
        * dataPin = pin to connect data channel (LoPy4 only)
        """
        self.ledNumber = ledNumber
        self.brightness = brightness

        # Prepare SPI data buffer (8 bytes for each color)
        self.buf_length = self.ledNumber * 3 * 8
        self.buf = bytearray(self.buf_length)

        # SPI init
        # Bus 0, 8MHz => 125 ns by bit, 8 clock cycle when bit transfert+2 clock cycle between each transfert
        # => 125*10=1.25 us required by WS2812
        if uname().sysname == 'LoPy4':
            self.spi = SPI(0, SPI.MASTER, baudrate=8000000, polarity=0, phase=1, pins=(None, dataPin, None))
             # Enable pull down (not working for LoPy4)
            # Pin(dataPin, mode=Pin.OUT, pull=Pin.PULL_DOWN)
        else: #WiPy
            self.spi = SPI(0, SPI.MASTER, baudrate=8000000, polarity=0, phase=1)
            # Enable pull down
            # Pin('P11', mode=Pin.OUT, pull=Pin.PULL_DOWN)

        # Turn LEDs off
        self.show([])
예제 #10
0
def get_fram():
    if uos.uname().machine.split(' ')[0][:4] == 'PYBD':
        Pin.board.EN_3V3.value(1)
        time.sleep(0.1)  # Allow decouplers to charge
    fram = FRAM(SPI(2, baudrate=25_000_000), cspins, size=512)  # Change size as required
    print('Instantiated FRAM')
    return fram
예제 #11
0
def welcome():
    pre = '|\t  '
    print('\n' * 2)
    print(' ', end='')
    print('.-v-' * 19)
    print('/' + pre)
    print('\\' + pre, end='')
    print('Welcome to %s %s @ %s.%s' %
          (cfg.package, cfg.version, cfg.hostname, cfg.domainname))
    print('/' + pre)
    print('\\' + pre)
    print('{' + pre, end='')
    print('MicroPython %s (Python %s) on the %s platform' % \
      ('.'.join(map(str,sys.implementation.version)), sys.version, sys.platform))
    print('/' + pre, end='')
    print('    (%s)' % uos.uname().version)
    print('\\' + pre)
    print('/' + pre, end='')
    try:
        print('Local time is %s, enjoy.' % date())
    except:
        pass
    print('\\' + pre)
    print('/' + pre, end='')
    print(' ' * 53, '~~`')
    print('\\' + pre)
    print('/' + pre, end='')
    print('   ... there is but only one way to death - through life.')
    print('\\' + pre)
    print('+', ',..,,' * 15)
    print('')
    print('')
    print('Loaded modules: %s' % ', '.join(sorted(list(sys.modules.keys()))))
예제 #12
0
 def __init__(self, pin, num_leds, address="0.0.0.0", port=8000):
     self.device_name = uos.uname()[0]
     self.pin = machine.Pin(pin, machine.Pin.OUT)  # configure pin for leds
     self.np = neopixel.NeoPixel(self.pin,
                                 num_leds)  # configure neopixel library
     self.address = address
     self.port = port
     self.animation_map = {
         "rainbow": self.rainbow,
         "rainbowChase": self.rainbowChase,
         "bounce": self.bounce,
         "chase": self.chase,
         "rgbFade": self.rgbFade,
         "altColors": self.altColors,
         "randomFill": self.randomFill,
         "fillFromMiddle": self.fillFromMiddle,
         "fillFromSides": self.fillFromSides,
         "fillStrip": self.fillStrip,
         "wipe": self.wipe,
         "sparkle": self.sparkle,
         "setStrip": self.setStrip,
         "setSegment": self.setSegment,
         "clear": self.clear,
     }
     self.running_anim = None
     self.statusLED = 5
     uasyncio.run(self.startupAnimation())
예제 #13
0
def get_eep():
    if uos.uname().machine.split(' ')[0][:4] == 'PYBD':
        Pin.board.EN_3V3.value(1)
        time.sleep(0.1)  # Allow decouplers to charge
    eep = EEPROM(I2C(2), T24C512)
    print('Instantiated EEPROM')
    return eep
예제 #14
0
파일: servo.py 프로젝트: lemariva/uPyIMU
    def __init__(self, gp_pin, channel, frequency, full_range100, pulse_min, pulse_max):
        """
        :param gp_pin: GPIO pin
        :channel: PWM unit
        :param frequency: in Hz
        :param full_range100: in deg
        :param pulse_min: in µs (WiPy3.0) in Duty (for ESP32, it should be - 30)
        :param pulse_max: in µs (WiPy3.0) in Duty (for ESP32, it should be - 30)
        :return:
        """

        # Store object properties
        self.PWM_frame = frequency  # in Hz
        self.full_range100 = full_range100
        self.pulse_min = pulse_min
        self.pulse_diff = pulse_max - pulse_min

    	self.min_position = 0
    	self.max_position = 180

        if (uname().sysname == 'WiPy'):
        	# Configure PWM timer to pin flow
        	self.pwm = PWM(0, frequency=self.PWM_frame)
        	self.servo = self.pwm.channel(channel, pin=gp_pin, duty_cycle=0.077)  # initial duty cycle of 7.5%
        else:
            self.pwm = PWM(gp_pin, freq=self.PWM_frame)
예제 #15
0
async def get_show(server, reader, writer, querystring, body):
    from template import render
    from rtc import get_dict_from_rtc

    uname = uos.uname()

    template_context = {
        'rtc_memory': repr(get_dict_from_rtc()),
        'sysname': uname.sysname,
        'nodename': uname.nodename,
        'id':
        ':'.join(['%02x' % char for char in reversed(machine.unique_id())]),
        'machine': uname.machine,
        'release': uname.release,
        'mpy_version': uname.version,
        'sys_modules': ', '.join(sorted(sys.modules.keys())),
        'minimal_modules': ', '.join(server.context.minimal_modules)
    }

    for attr_name in dir(server.context):
        if attr_name.startswith('_'):
            continue
        value = str(getattr(server.context, attr_name))
        print(attr_name, value)

        template_context[attr_name] = value

    await server.send_html_page(
        writer,
        filename='webswitch.html',
        content_iterator=render(filename='http_internals.html',
                                context=template_context,
                                content_iterator=None),
    )
예제 #16
0
    def _send_pulse_and_wait(self):
        """
        Send the pulse to trigger and listen on echo pin.
        We use the method `machine.time_pulse_us()` to get the microseconds until the echo is received.
        """
        self.trigger.value(0)  # Stabilize the sensor
        time.sleep_us(5)
        self.trigger.value(1)
        # Send a 10us pulse.
        time.sleep_us(10)
        self.trigger.value(0)
        try:
            if (uname().sysname == 'WiPy'):
                pulse_list = pulses_get(self.echo, self.echo_timeout_us)
                if (len(pulse_list) == 0):
                    pulse_time = -1
                else:
                    pulse_time = pulse_list[0][1]
            else:
                pulse_time = time_pulse_us(self.echo, 1, self.echo_timeout_us)

            return pulse_time
        except OSError as ex:
            if ex.args[0] == 110:  # 110 = ETIMEDOUT
                raise OSError('Out of range')
            raise ex
def get_sms(lte_comms):
    if uos.uname().sysname == 'FiPy':
        print("Starting to monitor for new SMS in 60 seconds")
        _thread.start_new_thread(lte_comms.receive_and_forward_to_chat, ())
        gc.collect()
    else:
        print("Not a fipy, not checking messages.")
예제 #18
0
    def __init__(self, ledNumber=1, brightness=100, dataPin='P22'):
        """
        Params:
        * ledNumber = count of LEDs
        * brightness = light brightness (integer : 0 to 100%)
        * dataPin = pin to connect data channel (LoPy only)
        """
        self.ledNumber = ledNumber
        self.brightness = brightness

        # Prepare SPI data buffer (8 bytes for each color)
        self.buf_length = self.ledNumber * 3 * 8
        self.buf = bytearray(self.buf_length)

        # SPI init
        # Bus 0, 8MHz => 125 ns by bit, 8 clock cycle when bit transfert+2 clock cycle between each transfert
        # => 125*10=1.25 us required by WS2812
        if uname().sysname == 'LoPy':
            self.spi = SPI(0, SPI.MASTER, baudrate=8000000, polarity=0, phase=1, pins=(None, dataPin, None))
             # Enable pull down
	    Pin(dataPin, mode=Pin.OUT, pull=Pin.PULL_DOWN)
	else: #WiPy
            self.spi = SPI(0, SPI.MASTER, baudrate=8000000, polarity=0, phase=1)
            # Enable pull down
            Pin('GP16', mode=Pin.ALT, pull=Pin.PULL_DOWN)
        
        # Turn LEDs off
        self.show([])
예제 #19
0
def get_device():
    if uos.uname().machine.split(' ')[0][:4] == 'PYBD':
        Pin.board.EN_3V3.value(1)
    # Adjust to suit number of chips and their wiring.
    cspins = (Pin(Pin.board.Y5, Pin.OUT,
                  value=1), Pin(Pin.board.Y4, Pin.OUT, value=1))
    flash = FLASH(SPI(2, baudrate=20_000_000), cspins, size=32768)
    print('Instantiated Flash')
    return flash
예제 #20
0
def get_eep(stm):
    if uos.uname().machine.split(' ')[0][:4] == 'PYBD':
        Pin.board.EN_3V3.value(1)
    if stm:
        eep = EEPROM(SPI(2, baudrate=5_000_000), cspins, 256)
    else:
        eep = EEPROM(SPI(2, baudrate=20_000_000), cspins)
    print('Instantiated EEPROM')
    return eep
예제 #21
0
async def record_wav_to_sdcard(audio_in, wav):
    sreader = asyncio.StreamReader(audio_in)

    # create header for WAV file and write to SD card
    wav_header = create_wav_header(
        SAMPLE_RATE_IN_HZ,
        WAV_SAMPLE_SIZE_IN_BITS,
        NUM_CHANNELS,
        SAMPLE_RATE_IN_HZ * RECORD_TIME_IN_SECONDS,
    )
    num_bytes_written = wav.write(wav_header)

    # allocate sample array
    # memoryview used to reduce heap allocation
    mic_samples = bytearray(10000)
    mic_samples_mv = memoryview(mic_samples)

    num_sample_bytes_written_to_wav = 0

    # continuously read audio samples from I2S hardware
    # and write them to a WAV file stored on a SD card
    print("Recording size: {} bytes".format(RECORDING_SIZE_IN_BYTES))
    print("==========  START RECORDING ==========")
    while num_sample_bytes_written_to_wav < RECORDING_SIZE_IN_BYTES:
        # read samples from the I2S peripheral
        num_bytes_read_from_mic = await sreader.readinto(mic_samples_mv)

        # write samples to WAV file
        if num_bytes_read_from_mic > 0:
            num_bytes_to_write = min(
                num_bytes_read_from_mic,
                RECORDING_SIZE_IN_BYTES - num_sample_bytes_written_to_wav)
            num_bytes_written = wav.write(mic_samples_mv[:num_bytes_to_write])
            num_sample_bytes_written_to_wav += num_bytes_written

    print("==========  DONE RECORDING ==========")
    # cleanup
    wav.close()
    if uos.uname().machine.find("PYBD") == 0:
        uos.umount("/sd")
    if uos.uname().machine.find("ESP32") == 0:
        uos.umount("/sd")
        sd.deinit()
    audio_in.deinit()
예제 #22
0
def i2s_callback_rx(arg):
    global state
    global num_sample_bytes_written_to_wav
    global mic_samples_mv
    global num_read

    if state == RECORD:
        num_bytes_written = wav.write(mic_samples_mv[:num_read])
        num_sample_bytes_written_to_wav += num_bytes_written
        # read samples from the I2S device.  This callback function
        # will be called after 'mic_samples_mv' has been completely filled
        # with audio samples
        num_read = audio_in.readinto(mic_samples_mv)
    elif state == RESUME:
        state = RECORD
        num_read = audio_in.readinto(mic_samples_mv)
    elif state == PAUSE:
        # in the PAUSE state read audio samples from the I2S device
        # but do not write the samples to SD card
        num_read = audio_in.readinto(mic_samples_mv)
    elif state == STOP:
        # create header for WAV file and write to SD card
        wav_header = create_wav_header(
            SAMPLE_RATE_IN_HZ,
            WAV_SAMPLE_SIZE_IN_BITS,
            NUM_CHANNELS,
            num_sample_bytes_written_to_wav //
            (WAV_SAMPLE_SIZE_IN_BYTES * NUM_CHANNELS),
        )
        pos = wav.seek(
            0)  # advance to first byte of Header section in WAV file
        num_bytes_written = wav.write(wav_header)
        # cleanup
        wav.close()
        if uos.uname().machine.find("PYBD") == 0:
            uos.umount("/sd")
        if uos.uname().machine.find("ESP32") == 0:
            uos.umount("/sd")
            sd.deinit()
        audio_in.deinit()
        print("Done")
    else:
        print("Not a valid state.  State ignored")
예제 #23
0
def main():
    print('=' * 45)
    print()

    # Read the Temperature
    if 'esp32' in uname().sysname:
        field1 = round(tmp36.read_temp(int(ADC_PIN), 'F'), 1)
    elif 'esp8266' in uname().sysname:
        field1 = round(tmp36.read_temp(0, 'F'), 1)  # Only one ADC on PIN 0
    print('Temperature Reading: %sF' % field1)

    # Send the Data to Server
    response = iot_api(server, port, client_id, field1)
    if response:
        print('Upload: Success')
        print()
    else:
        print('Upload: Failed')
        sleep(sleep_interval)
        reset()
def read_adc(gpio_pin_number):
    '''Read the Raw ADC value one time'''
    if 'esp32' in uname().sysname:
        # Source: https://docs.micropython.org/en/latest/esp32/quickref.html#adc-analog-to-digital-conversion
        from machine import Pin
        adc = ADC(Pin(gpio_pin_number))  # Pins 32-39 are valid
        adc.atten(ADC.ATTN_6DB
                  )  # 0-2V since the TMP36 data pin is min 0.1V and max 1.75V
        adc.width(ADC.WIDTH_12BIT)  # 0-4095 values
        # millivolts = average_adc * (2000/4095)  # Example: 750mV = 1535.6 * (2000/4095)
    elif 'esp8266' in uname().sysname:
        adc = ADC(
            0
        )  # gpio_pin_number is ignored since there is only one ADC on ESP8266
        # ADC values from 0 to 1023
        # millivolts = average_adc * (3300/1023)  # Example: 750mV =  232.5 * (3300/1023)
    else:
        print('unknown hardware')
        exit(1)
    return adc.read()
예제 #25
0
def print_system_info():
    os_info = uos.uname()

    print("os info:")
    print("  node: %s" % os_info.nodename)
    print("  release: %s, version: %s" % (os_info.release, os_info.version))
    print("  cpu freq: %d MHz" % int(machine.freq() / (1000**2)))
    print("")

    # print stack and heap info
    machine.info()
예제 #26
0
 def dev(self):
     # Device
     # Meta data object.
     # HA will use this to group all components that belong to the same device and prevent duplicates.
     return dict(
         mf = self.MANUF,
         sw = uname().release + '/' + VERSION,
         mdl = self.dev_name,
         ids = self.uid,
         name = self.ful_dev_name(),
     )
예제 #27
0
def main():
    gc.collect()  # Loop runs device out of memory without this
    #print('Free Memory: %sKB' % int(gc.mem_free()/1024))

    # Send the Data to Server
    data = read_sensor()
    print(data)
    response = urequests.post(url, headers=headers, data=data)
    if '204' in str(
            response.status_code
    ):  # HTTP Status 204 (No Content) indicates server fulfilled request
        print('InfluxDB write: Success')
        print()
        if 'TinyPICO' in uname().machine:
            led.blink(0, 255, 0, ms=1500, i=1)  # Green
    else:
        print('InfluxDB write: Failed (%s)' % (response.status_code))
        if 'TinyPICO' in uname().machine:
            led.solid(255, 127, 0)  # Orange
        sleep(sleep_interval)
        reset()
예제 #28
0
파일: servo.py 프로젝트: lemariva/uPyIMU
 def angle(self, angle100):
     """
     Set timer duty cycle to specified angle
     :param angle100: angle in deg * 100
     :return:
     """
     angle_fraction = float(angle100) / float(self.full_range100)
     pulse_width = float(self.pulse_min + angle_fraction * self.pulse_diff) # in µs
     if (uname().sysname == 'WiPy'):
         duty_cycle =  pulse_width * 100 / (1000 / self.PWM_frame) / 100
         self.servo.duty_cycle(duty_cycle)
     else:
         self.pwm.duty(int(pulse_width))
예제 #29
0
 def send_health_info(self, mqttc,ipaddr,mask):
     try:
                 os = uos.uname()
                 print (os)
                 message = {"value": "ok","version":os.version,"ipaddress":ipaddr,"ipmask":mask,"time":self.PrintTime(self.rtc.datetime())}
                 mqttc.publish(self.config["board"]["system"]["topic"]["publish"]+"/" + self.config["board"]
                               ["id"], ujson.dumps(message))
                 print("health "+self.config["board"]["id"]+" ok")
        
     except BaseException as e:
         print("sensors:An exception occurred during health reading")
         import sys
         sys.print_exception(e)
예제 #30
0
def board_info():
	import sys
	import uos
	import machine
	sw_impl = sys.implementation[0]
	sw_ver = sys.implementation[1]
	uname = uos.uname()
	freq = machine.freq() / 1000000

	print('')
	print('Software: {} {}'.format(sw_impl, sw_ver) )
	print('Uname: {}'.format(uname) )
	print('Frequency: {} Mhz'.format(freq) )
	print('WAKE Reason:', machine.reset_cause())
	print('')
def main():

    gc.collect(
    )  # Free up Heap space after each loop to avoid urequests memory leak
    # Uncomment to monitor RAM usage
    #print('Free Memory: %sKB' % int(gc.mem_free()/1024))

    # Read the TMP36 Sensor
    if adc_min is '':
        temperature = round(AnalogDevices_TMP36.read_temp(int(ADC_PIN)), 1)
    else:
        temperature = round(
            AnalogDevices_TMP36.temp_calibrated(int(ADC_PIN), int(adc_min),
                                                int(adc_max), float(temp_min),
                                                float(temp_max)), 1)
    #print('Fahrenheit: %.01f' % temperature)

    # Send the Data to Server (Try to avoid '-' and '_' characters in InfluxDB Key names)
    data = "%s,clientid=%s temperature=%.01f" % (measurement, client_id,
                                                 temperature)
    print(data)
    response = urequests.post(url, headers=headers, data=data)
    #print('STATUS:', response.status_code)
    if '204' in str(
            response.status_code
    ):  # HTTP Status 204 (No Content) indicates server successfull fulfilled request with no response content
        print('InfluxDB write: Success')
        print()
        if 'TinyPICO' in uname().machine:
            led.blink(0, 255, 0, ms=1500, i=1)  # Green
    else:
        print('InfluxDB write: Failed')
        if 'TinyPICO' in uname().machine:
            led.solid(255, 127, 0)  # Orange
        sleep(sleep_interval)
        reset()