예제 #1
0
def do_mqtt_connect(config):
    from umqtt.simple import MQTTClient
    global mqttc
    try:
        # print(config)
        mqttc = MQTTClient(client_id=config["board"]["id"],
                           server=config["mqtt"]["server"],
                           user=config["mqtt"]["user"],
                           password=config["mqtt"]["password"],
                           keepalive=60)
        registerjs = {}
        registerjs["id"] = config["board"]["id"]
        registerjs["flash_id"] = esp.flash_id()
        # registerjs["machine_id"]=str(machine.unique_id().decode())
        print(registerjs)
        #registerjs["capabilities"]= config["board"]["capabilities"]
        # mqttc.set_last_will(config["mqtt"]["topic"]["unregister"],ujson.dumps(registerjs))
        mqttc.connect()
        mqttc.publish(config["mqtt"]["topic"]["register"],
                      ujson.dumps(registerjs))

        #global dhtsensor
        #dhtsensor = dht.DHT22(machine.Pin(config["board"]["pins"]["dht"]))

        mqttc.set_callback(mqtt_subscribe)
        mqttc.subscribe(config["mqtt"]["topic"]["subscribe"] + "/" +
                        config["board"]["id"] + "/#",
                        qos=1)
        mqttc.subscribe(config["mqtt"]["topic"]["broadcast"] + "/#", qos=1)

    except BaseException as e:
        print("An exception occurred during do_mqtt_connect")
        import sys
        sys.print_exception(e)
예제 #2
0
 def get_esp_stats(self):
     import esp
     return {
         'flash_id': esp.flash_id(),
         'flash_size': esp.flash_size(),
         'free_mem': esp.freemem()
     }
예제 #3
0
 def get_esp_stats(self):
     import esp
     return {
         'flash_id': esp.flash_id(),
         'flash_size': esp.flash_size(),
         'free_mem': esp.freemem()
     }
예제 #4
0
def main():

    ROM = uctypes.bytearray_at(0x40200000, 16)
    fid = esp.flash_id()

    print("FlashROM:")
    print("Flash ID: %x (Vendor: %x Device: %x)" %
          (fid, fid & 0xFF, fid & 0xFF00 | fid >> 16))

    print("Flash bootloader data:")
    SZ_MAP = {0: "512KB", 1: "256KB", 2: "1MB", 3: "2MB", 4: "4MB"}
    FREQ_MAP = {0: "40MHZ", 1: "26MHZ", 2: "20MHz", 0xF: "80MHz"}
    print("Byte @2: %02x" % ROM[2])
    print("Byte @3: %02x (Flash size: %s Flash freq: %s)" %
          (ROM[3], SZ_MAP.get(ROM[3] >> 4, "?"), FREQ_MAP.get(ROM[3] & 0xF)))
    print("Firmware checksum:")
    print(esp.check_fw())

    print("\nNetworking:")
    print("STA ifconfig:", network.WLAN(network.STA_IF).ifconfig())
    print("AP ifconfig:", network.WLAN(network.AP_IF).ifconfig())
    print("Free WiFi driver buffers of type:")
    for i, comm in enumerate(("1,2 TX", "4 Mngmt TX(len: 0x41-0x100)",
                              "5 Mngmt TX (len: 0-0x40)", "7", "8 RX")):
        print("%d: %d (%s)" % (i, esp.esf_free_bufs(i), comm))
    print("lwIP PCBs:")
    lwip.print_pcbs()
예제 #5
0
def do_mqtt_boot_connect(config):
    from umqtt.simple import MQTTClient
    global mqttc
    try:
        # print(config)
        mqttc = MQTTClient(client_id=config["board"]["id"],
                           server=config["mqtt"]["server"],
                           user=config["mqtt"]["user"],
                           password=config["mqtt"]["password"],
                           keepalive=60)
        registerjs = {}
        registerjs["id"] = config["board"]["id"]
        registerjs["flash_id"] = esp.flash_id()
        registerjs["msg"] = {'action': 'bootstrap'}
        registerjs["systemtime"] = timeStr(rtc.datetime())
        # registerjs["machine_id"]=str(machine.unique_id().decode())
        print(registerjs)
        #registerjs["capabilities"]= config["board"]["capabilities"]
        # mqttc.set_last_will(config["mqtt"]["topic"]["unregister"],ujson.dumps(registerjs))
        mqttc.connect()
        mqttc.publish(config["mqtt"]["topic"]["register"],
                      ujson.dumps(registerjs))
        mqttc.set_callback(mqtt_boot_subscribe)
        mqttc.subscribe(config["mqtt"]["topic"]["subscribe"] + "/" +
                        config["board"]["id"] + "/#",
                        qos=1)
    except BaseException as e:
        print("An exception occurred during do_mqtt_boot_connect")
        import sys
        sys.print_exception(e)
예제 #6
0
파일: acf_network.py 프로젝트: Paumanok/ACF
 def getNewKey(self):
     resp = r.post('http://' + self.wlan.ifconfig()[2] +
                   ":5000/sfeeder/config",
                   json={
                       'id': esp.flash_id(),
                       'key': newkey_key
                   },
                   headers={'Content-Type': 'application/json'})
     b = resp.json()['bool']
     key = resp.json()['key']
     return (b, key)
예제 #7
0
def main():

    ROM = uctypes.bytearray_at(0x40200000, 16)
    fid = esp.flash_id()

    print("Flash ID: %x (Vendor: %x Device: %x)" %
          (fid, fid & 0xff, fid & 0xff00 | fid >> 16))

    print("Flash bootloader data:")
    SZ_MAP = {0: "512KB", 1: "256KB", 2: "1MB", 3: "2MB", 4: "4MB"}
    FREQ_MAP = {0: "40MHZ", 1: "26MHZ", 2: "20MHz", 0xf: "80MHz"}
    print("Byte @2: %02x" % ROM[2])
    print("Byte @3: %02x (Flash size: %s Flash freq: %s)" %
          (ROM[3], SZ_MAP.get(ROM[3] >> 4, "?"), FREQ_MAP.get(ROM[3] & 0xf)))
예제 #8
0
def main():
    print("Hello Welcome to SYDCA ESP OS")

    print("Flash_id:" + str(esp.flash_id()))
    machid = str(machine.unique_id())
    machid = ure.sub("\\\\x", "", machid)
    machid = ure.sub("b'", "", machid)
    machid = ure.sub("'", "", machid)
    print("Machine Id:" + str(machid))
    print("Flash Size:" + str(esp.flash_size()))
    boot_init()
    # print(initfile.readlines())
    print("Start Running Mode")
    load_init_file()
 def get_flash_stats(self):
     stats = os.statvfs('/')
     frsize = stats[1]
     blocks = stats[2]
     bavail = stats[4]
     capacity = blocks * frsize
     free = bavail * frsize
     used = capacity - free
     return {
         'flash_id': esp.flash_id(),
         'flash_size': esp.flash_size(),
         'capacity': capacity,
         'used': used,
         'free': free
     }
예제 #10
0
def do_get(clisock, uri, content_length):
    clisock.write(b'HTTP/1.0 200 OK\r\n'
        b'Content-type: text/html; charset=utf-8\r\n'
        b'\r\n')
    clisock.write(b'<!DOCTYPE html><html><head><title>Current time</title></head>')
    clisock.write(b'<body>The current time is: ')
    timestr ='{}-{:02d}-{:02d} {:02d}:{:02d}:{:02d}'.format(*time.localtime())
    clisock.write(timestr.encode('ascii'))
    del timestr
    uptime_s = int(time.ticks_ms() / 1000)
    uptime_h = int(uptime_s / 3600)
    uptime_m = int(uptime_s / 60)
    uptime_m = uptime_m % 60
    uptime_s = uptime_s % 60
    
    clisock.write(b'<p>Uptime: {:02d}h {:02d}:{:02d}'.format(
        uptime_h, uptime_m, uptime_s))

    clisock.write(b'<p>Flash ID: {:x}'.format(esp.flash_id()))
    clisock.write(b'<p>Flash size: {:d}'.format(esp.flash_size()))
    clisock.write(b'<p>Python: {:s} on {:s} '.format(str(sys.implementation), sys.platform))
    clisock.write(b'<p>Unique ID: ')
    for b in machine.unique_id():
        clisock.write(b'{:02x}'.format(b))
    clisock.write(b'\n<h2>Network interfaces</h2>\n')
    clisock.write(b'\n<table><tr><th>mac<th>active</th><th>connected</th><th>IP</th><th>Gateway</th>')
    for i in network.STA_IF, network.AP_IF:
        wlan = network.WLAN(i)
        # Show MAC address.
        clisock.write(b'<tr>')
        clisock.write(b'<td>')
        for b in wlan.config('mac'):
            clisock.write(b'{:02X}'.format(b))

        clisock.write(b'<td>{:}</td>'.format(wlan.active()))
        clisock.write(b'<td>{:}</td>'.format(wlan.isconnected()))
        ifconfig = wlan.ifconfig() #ip, netmask, gateway, dns
        ifconfig = (ifconfig[0], ifconfig[2]) # ip, gw
        for item in ifconfig:
            clisock.write(b'<td>{:}</td>'.format(item))

    clisock.write(b'\n</table>\n')
예제 #11
0
def main():

    ROM = uctypes.bytearray_at(0x40200000, 16)
    fid = esp.flash_id()

    print("FlashROM:")
    print("Flash ID: %x (Vendor: %x Device: %x)" % (fid, fid & 0xff, fid & 0xff00 | fid >> 16))

    print("Flash bootloader data:")
    SZ_MAP = {0: "512KB", 1: "256KB", 2: "1MB", 3: "2MB", 4: "4MB"}
    FREQ_MAP = {0: "40MHZ", 1: "26MHZ", 2: "20MHz", 0xf: "80MHz"}
    print("Byte @2: %02x" % ROM[2])
    print("Byte @3: %02x (Flash size: %s Flash freq: %s)" % (ROM[3], SZ_MAP.get(ROM[3] >> 4, "?"), FREQ_MAP.get(ROM[3] & 0xf)))

    print("\nNetworking:")
    print("Free WiFi driver buffers of type:")
    for i in range(5):
        print("%d: %d" % (i, esp.esf_free_bufs(i)))
    print("lwIP PCBs:")
    lwip.print_pcbs()
예제 #12
0
    def __init__(self):

        if hasattr(config, 'DEVICE_ID'):
            self.device_id = config.DEVICE_ID
        else:
            self.device_id = 'mp-' + str(esp.flash_id())

        if hasattr(config, 'SEND_INTERVAL_SECONDS'):
            self.sendIntervalSeconds = config.SEND_INTERVAL_SECONDS
        else:
            self.sendIntervalSeconds = DEFAULT_SEND_INTERVAL_SECONDS

        try:
            from display import Display
            self.display = Display()
        except ImportError:
            self.display = None

        try:
            from sht30 import SHT30
            self.sensor = SHT30()
        except ImportError:
            self.sensor = None

        try:
            from moisture import SoilMoistureSensor
            self.soilMoistureSensor = SoilMoistureSensor()
        except ImportError:
            self.soilMoistureSensor = None

        try:
            from mhz19 import MHZ19
            self.mhz19 = MHZ19()
            self.mhz19.start()
        except ImportError:
            self.mhz19 = None

        disable_access_point()
        do_connect(WLAN_SSID, WLAN_PASSWORD)

        self.ntptimeWhenZero = 0
예제 #13
0
def main():

    ROM = uctypes.bytearray_at(0x40200000, 16)
    fid = esp.flash_id()

    print("FlashROM:")
    print("Flash ID: %x (Vendor: %x Device: %x)" %
          (fid, fid & 0xff, fid & 0xff00 | fid >> 16))

    print("Flash bootloader data:")
    SZ_MAP = {0: "512KB", 1: "256KB", 2: "1MB", 3: "2MB", 4: "4MB"}
    FREQ_MAP = {0: "40MHZ", 1: "26MHZ", 2: "20MHz", 0xf: "80MHz"}
    print("Byte @2: %02x" % ROM[2])
    print("Byte @3: %02x (Flash size: %s Flash freq: %s)" %
          (ROM[3], SZ_MAP.get(ROM[3] >> 4, "?"), FREQ_MAP.get(ROM[3] & 0xf)))

    print("\nNetworking:")
    print("Free WiFi driver buffers of type:")
    for i in range(5):
        print("%d: %d" % (i, esp.esf_free_bufs(i)))
    print("lwIP PCBs:")
    lwip.print_pcbs()
예제 #14
0
 def process(self, url, params):
     if url == '/':
         data = {}
         gc.collect()
         data['nodemcu'] = {}
         data['nodemcu']['mem_free'] = gc.mem_free()
         data['nodemcu']['flash_id'] = esp.flash_id()
         data['nodemcu']['chip_id'] = utils.chipId()
         data['nodemcu']['bootreason'] = machine.reset_cause()
         data['nodemcu']['voltage'] = self.adc.read() / 1000.0
         data['python'] = {}
         data['python']['implementation'] = self.implementation()
         data['python']['version'] = sys.version
         data['datetime'] = {}
         data['datetime']['formatted'] = self.datetime()
         data['datetime']['seconds'] = utime.time()
         data['uptime'] = {}
         data['uptime']['formatted'] = self.uptime()
         data['uptime']['seconds'] = int(utime.ticks_ms() / 1000)
         (ssid, hostname, rssi) = self.ssidAndRssi()
         data['network'] = {}
         data['network']['local'] = {}
         data['network']['local']['mac'] = ubinascii.hexlify(
             self.wlan.config('mac'), ':').decode()
         data['network']['local']['ip'] = self.wlan.ifconfig()[0]
         data['network']['local']['hostname'] = hostname
         data['network']['wifi'] = {}
         data['network']['wifi']['ssid'] = ssid
         data['network']['wifi']['rssi'] = rssi
         data['controllers'] = [c.name()
                                for c in self.controllers] + [self.name()]
         data['device_type'] = self.deviceType
         return ujson.dumps(data)
     elif url == '/REBOOT/' or url == '/RESET/':
         machine.Timer(0).init(period=1000,
                               mode=machine.Timer.PERIODIC,
                               callback=lambda t: machine.reset())
         return utils.jsonResponse(
             200, "Board will be restarted in a few seconds")
예제 #15
0
def main():

    ROM = uctypes.bytearray_at(0x40200000, 16)
    fid = esp.flash_id()

    print("FlashROM:")
    print("Flash ID: %x (Vendor: %x Device: %x)" % (fid, fid & 0xff, fid & 0xff00 | fid >> 16))

    print("Flash bootloader data:")
    SZ_MAP = {0: "512KB", 1: "256KB", 2: "1MB", 3: "2MB", 4: "4MB"}
    FREQ_MAP = {0: "40MHZ", 1: "26MHZ", 2: "20MHz", 0xf: "80MHz"}
    print("Byte @2: %02x" % ROM[2])
    print("Byte @3: %02x (Flash size: %s Flash freq: %s)" % (ROM[3], SZ_MAP.get(ROM[3] >> 4, "?"), FREQ_MAP.get(ROM[3] & 0xf)))
    print("Firmware checksum:")
    print(esp.check_fw())

    print("\nNetworking:")
    print("STA ifconfig:", network.WLAN(network.STA_IF).ifconfig())
    print("AP ifconfig:", network.WLAN(network.AP_IF).ifconfig())
    print("Free WiFi driver buffers of type:")
    for i, comm in enumerate(("1,2 TX", "4 Mngmt TX(len: 0x41-0x100)", "5 Mngmt TX (len: 0-0x40)", "7", "8 RX")):
        print("%d: %d (%s)" % (i, esp.esf_free_bufs(i), comm))
    print("lwIP PCBs:")
    lwip.print_pcbs()
예제 #16
0
    elif real_size == 2048 * 1024:
        code = 3
    elif real_size == 4096 * 1024:
        code = 4
    else:
        code = 2
    buf = bytearray(4096)
    esp.flash_read(0, buf)
    buf[3] = (buf[3] & 0xf) | (code << 4)
    esp.flash_erase(0)
    esp.flash_write(0, buf)


# If bootloader size ID doesn't correspond to real Flash size,
# fix bootloader value and reboot.
size = esp.flash_id() >> 16
# Check that it looks like realistic power of 2 for flash sizes
# commonly used with esp8266
if 22 >= size >= 18:
    size = 1 << size
    if size != esp.flash_size():
        import machine
        import time
        print(
            "Bootloader Flash size appear to have been set incorrectly, trying to fix"
        )
        set_bl_flash_size(size)
        machine.reset()
        while 1:
            time.sleep(1)
예제 #17
0
station.active(True)

station.connect(ssid, password)

while station.isconnected() == False:
    pass

webrepl.start()

try:
    settime()
    log('set time successful!')
except:
    log('set time failed!!!')

log('Connection successful')
log('Controller IP: ' + str(station.ifconfig()[0]))
log('Allocated Heap: ' + str(gc.mem_alloc()))
log('Free Heap: ' + str(gc.mem_free()))
log('Flash ID: ' + str(esp.flash_id()))
log('Flash Size: ' + str(esp.flash_size()))
log('Current hour: ' + str(utime.localtime()[3] + 7))
log('UTC DateTime: ' + str(utime.localtime()))

day = str((utime.localtime()[2]))
hour = str(int((utime.localtime()[3]) + 7))
min = str((utime.localtime()[4]))

log('-->Boot completed at day:' + day + ' hour:' + hour + ' min:' + min)
예제 #18
0
        code = 2
    elif real_size == 2048*1024:
        code = 3
    elif real_size == 4096*1024:
        code = 4
    else:
        code = 2
    buf = bytearray(4096)
    esp.flash_read(0, buf)
    buf[3] = (buf[3] & 0xf) | (code << 4)
    esp.flash_erase(0)
    esp.flash_write(0, buf)

# If bootloader size ID doesn't correspond to real Flash size,
# fix bootloader value and reboot.
size = esp.flash_id() >> 16
# Check that it looks like realistic power of 2 for flash sizes
# commonly used with esp8266
if 22 >= size >= 18:
    size = 1 << size
    if size != esp.flash_size():
        import machine
        import time
        print("Bootloader Flash size appear to have been set incorrectly, trying to fix")
        set_bl_flash_size(size)
        machine.reset()
        while 1: time.sleep(1)

size = esp.flash_size()
if size < 1024*1024:
    bdev = None
예제 #19
0
crawl_motor = Servo(motor3)

sleep(1)

# inicializalas, azaz mindegyik motor 0 pozicioba allitasa
servomotor.write_angle(0)  
servomotor2.write_angle(0)  
crawl_motor.write_angle(0)  

# valtozok, melyek az aktualis allasszoget tartalmazzak
servo_angle = 0
servo2_angle = 0
crawl_angle = 0

# eszkoz egyedi azonositojanak lekerese, ezt hasznaljuk a wifi halozat neveben
id = esp.flash_id()
wifi_name = "RobotKar-YOUR-NAME-" + str(id) 
print("Eszkoz WiFi azonositoja: " + str(wifi_name))

# "access point" azaz WiFi halozati eleresi pont definialasa
ap = network.WLAN(network.AP_IF) 
ap.active(True)         
ap.config(essid=wifi_name, authmode=0) 

# eleresi pont (WiFi halozat) IP cimenek kiirasa
print(ap.ifconfig()[0])

def web_page():

  # weboldal valtozoinak beallitasa annak erdekeben,  
  # hogy a motor ne terhessen ki a megengedett allasszog tartomanybol (0-180 fok)
# upip packages - see README.md
# upip.install('micropython-umqtt.simple')
# upip.install('micropython-umqtt.robust')

ap_if = network.WLAN(
    network.AP_IF)  # turn off the access point which is on by default
ap_if.active(False)

cfg = config.Config('config.json')

if cfg.isEsp8266:
    BuiltinLedPin = 2
    i2c = I2C(scl=Pin(5), sda=Pin(4))
    adc = ADC(0)  # create ADC object on ADC pin
    mqttId = str(esp.flash_id())
    esp.sleep_type(esp.SLEEP_LIGHT)
else:
    BuiltinLedPin = 5
    i2c = I2C(scl=Pin(22), sda=Pin(21))
    adc = None
    import urandom as random
    mqttId = str(random.randint(100, 100000))

builtinLed = Pin(BuiltinLedPin, Pin.OUT)

mySensor = cfg.sensor.Sensor(i2c)

client = MQTTClient(mqttId, cfg.mqttBroker)
sta_if.connect(cfg.wifiSsid, cfg.wifiPwd)
예제 #21
0
            machine.RTC().datetime(tm)
            return utime.localtime()
        except:
            time.sleep(1)
            pass


def getUrlEncodedDate():
    #Needs a try catch
    (year, month, day, hour, minute, second, x, y) = gettime()
    return '{0}-{1}-{2}%20{3}%3A{4}%3A{5}'.format(year, month, day, hour,
                                                  minute, second)
    #print('Sending')


id = '{0:x}'.format(esp.flash_id())
manufacturer = id[-2:]
device_id = id[2:4] + id[0:2]

print('Starting device: ', device_id)

do_connect()

i2c = machine.I2C(-1, machine.Pin(5), machine.Pin(4))
led = machine.Pin(15, machine.Pin.OUT)
address = 24
temp_reg = 5
res_reg = 8

data = bytearray(2)
예제 #22
0
def get_device_id():
    """ GEt unique id for device"""
    flash_id = '{0:x}'.format(esp.flash_id())
    manufacturer = flash_id[-2:]
    device_id = flash_id[2:4] + flash_id[0:2]
    return (manufacturer, device_id)
예제 #23
0
import uhashlib
import json

esp.osdebug(None)
machine.freq(160000000)
micropython.alloc_emergency_exception_buf(200)

wlan = network.WLAN(network.STA_IF)
ap = network.WLAN(network.AP_IF)

SOFT_RESET = const(4)
SLEEP_RESET = const(5)
HARD_RESET = const(6)

print()
print('FLASH ID:    %s' % hex(esp.flash_id()))
print('WLAN MAC:    %s' % ':'.join('%02X' % b for b in wlan.config("mac")))
print('AP MAC:      %s' % ':'.join('%02X' % b for b in ap.config("mac")))

gc.collect()

print('Initial setup...')

DAYS = ("Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun")

# Pinouts:
PIN_SCL = const(5)
PIN_SDA = const(4)

PIN_HEATING = const(12)
PIN_COOLING = const(13)