BLYNK
BLYNK.IO       📲 GETTING STARTED       đź“— DOCS       👉 SKETCH BUILDER

microPython: Keep getting "AttributeError: 'module' object has no attribute 'Blynk'"

As I have not been able to find documentation for how often Blynk.run should be called I have set up a small scheduler which sends one Blynk command every 100 ms till done (max 8 commands in total - 3 colors, 4 values, one Push )
Library installed in root of the ESP.
I am running this on a hacked Sonoff Basic using Vshymanskyy’s blynk-library-python from github.


BLYNK_AUTH =    'kTFRmx7VgEtXb2aEUMyAo....HqSsFG6'
import blynklib
blynk = blynklib.Blynk(BLYNK_AUTH)

import network
import machine
from machine import Pin
from machine import Timer
import onewire
import ds18x20

#import sys
import time
import ntptime
from machine import RTC

_DAYS_IN_MONTH = [None, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]

WIFI_SSID =     'xxxxxxxxxx'
WIFI_PASS =     'yyyyyyyyy'


BLYNK_GREEN =   "#23C48E"
BLYNK_YELLOW =  "#ED9D00"
BLYNK_RED =     "#D3435C"
LED_HIGH =      255

#Virtual pins
V0 =       0
V1 =       1
V2 =       2
V3 =       3
Virtuals = (V0,V1,V2,V3,V0,V1,V2,V3) #the virtual pins are handles one by one from this list


SleepTime =    30*60*1000    # half an hour is max sleep time 
tempLimit =    -18           # maximum acceptable temperature in freezer
tempRange =    6             # range where temp is somewhat acceptable

msg =  ""
col =  0
temp = -30

rtc = RTC()

# check if the device woke from a deep sleep
#if machine.reset_cause() == machine.DEEPSLEEP_RESET:
#    print('woke from a deep sleep')

# set up the OneWire communication to the temperature sensor
ow = onewire.OneWire(Pin(14))
ds = ds18x20.DS18X20(ow)

#lcd.putstr("Trigger ds18x20\n")
roms = ds.scan()
 
f = open('checktime.txt')
flag = f.read()
f.close()
f = open('checktime.txt', 'w')
#Toggle the Flag
if flag == 'Wait':
    f.write("Go  ")
else:
    f.write("Wait")
f.close()
print("flag " + flag)
if flag == 'Wait':
    msgNo = 16            # this wil force a deepsleep as first job in scheduler
else:
    msgNo = -1
    
print("Connecting to WiFi...")
wifi = network.WLAN(network.STA_IF)
wifi.active(True)
wifi.connect(WIFI_SSID, WIFI_PASS)
while not wifi.isconnected():
    pass
print('IP:', wifi.ifconfig()[0])
#lcd.putstr(str(wifi.ifconfig()[0]) + "\n")


def setTime():
    try:
        ntptime.settime()
        print('synced from server: ' + ntptime.host)
        return True
    except OSError:
        print('Couldn\'t retrieve time')
        return False

# synchronize with ntp
# need to be connected to wifi

if setTime():
    pass
else:
    time.sleep(10) # sleep for 10 sec before trying again
    setTime()

t = rtc.datetime()    # get the date and time in UTC
day =    t[2]
month =  t[1]
year =   t[0]
hour =   t[4]
minute = t[5]

#Adjust for one hour difference to UTC
if ((year % 4) == 0) and (month == 2): # leap year and month = february
    extra = 1
else:
    extra = 0
    
if hour == 23:
    hour = 0
    if day == _DAYS_IN_MONTH[month] + extra: # if leap year and month = februar, add one day
        day = 1
        if month == 12:
            month = 1
            year = year + 1
        else:
            month = month + 1
    else:
        day = day + 1
else:
    hour = hour + 1
    
print(day,month,year,hour,minute)
   
def initiateTemp():
    ds.convert_temp() # linitiate a reading
    print("a Temp reading was Triggered")
    
def readTemp():
    global msg
    global col
    global temp
    for rom in roms: # now read the temperature
        temp = ds.read_temp(rom)
        msg = "Temp: {:+.1f}".format(temp)        
    for i in range(len(msg)+1,17):
        msg = msg + " "
    print(msg)
    # Set the Blynk color based on temp
    if temp <= tempLimit:
        col = _GREEN
    elif (temp > tempLimit) and (temp <= (tempLimit + tempRange)):
        col = BLYNK_YELLOW
    else:
        col = BLYNK_RED
    
def wait(): #wait for temp reading to settle
    pass

def notify():
    print("notify")
    if col == BLYNK_YELLOW: 
        blynk.notify("Dybfryser temperatur over -18 grader: {:.1f}".format(temp)) # Houston we have a problem!
    elif col == BLYNK_RED:
        blynk.notify("Dybfryser temperatur langt over -18 grader: {:.1f}".format(temp))  # Houston we have a huge problem!
        
def colors():
    print("colors " + str(Virtuals[msgNo]))
    blynk.set_property(Virtuals[msgNo],"color",col) # All graphs, LEDs and Gauges set to color "col"
        
def values():
    print("values " + str(Virtuals[msgNo]))
    blynk.virtual_write(Virtuals[msgNo],temp)  # send data to the virtuals
   
def LED():
    print("LED " + str(Virtuals[msgNo]))
    blynk.virtual_write(Virtuals[msgNo],LED_HIGH)  # send data to the LED (Intensity)
    
def deep_sleep(msecs):
  # configure RTC.ALARM0 to be able to wake the device
  rtc = machine.RTC()
  rtc.irq(trigger=rtc.ALARM0, wake=machine.DEEPSLEEP)
  # set RTC.ALARM0 to fire after X milliseconds (waking the device)
  rtc.alarm(rtc.ALARM0, msecs)
  # put the device to sleep
  machine.deepsleep()

def gotosleep():
    global msgNo
    #lcd.clear
    #lcd.putstr("    Sleeping    ")
    #lcd.putstr(msg)
    print("See you later")
    deep_sleep(SleepTime)  # and then go to sleep again for 30 minutes

def translate2functions(argument):
    print ("Dispather " + str(argument))
    switcher = {
        0:  initiateTemp,
        1:  wait,
        2:  wait,
        3:  wait,
        4:  wait,
        5:  wait,
        6:  wait,
        7:  wait,
        8:  readTemp,
        9:  notify,
        10: colors,
        11: colors,
        12: colors,
        13: values,
        14: values,
        15: values,
        16: LED,
        17: gotosleep  # end the show
    }
    # Get the function from switcher dictionary    
    func = switcher.get(argument)
    # Execute the function on return!
    return func()

def DoJobs():
    global msgNo
    msgNo = (msgNo + 1) 
    print("DoJobs " + str(msgNo))
    translate2functions(msgNo)

#Start the scheduler:
tim0 = Timer(-1) # construct a virtual timer
tim0.init(period=100, mode=Timer.PERIODIC, callback=lambda t:DoJobs()) 

while true
    blynk.run()

@riteman2 please edit your post to add triple backticks at the beginning and end of your code so that it displays correctly.
Triple backticks look like this:
```

The characters you used aren’t the correct ones.

Pete.

Thanks - just modified the post

Lars

Please paste the whole error text, as it tends to show details and location of the offending error… else it is just a big fat guessing game.

Error text is as stated in the headline and it points to the statement
blynk = blynklib.Blynk(BLYNK_AUTH)
If I move that statement around the pointer in the errormessage moves as well.

Lars

We use the headline as just what it is… a title. If you expect help then clear details are needed in the body of the topic.

For example… when testing your above full code I get various errors… the closest to your interpretation is this…

==================== RESTART: /home/pi/Blynk user test.py ====================
Traceback (most recent call last):
  File "/home/pi/Blynk user test.py", line 2, in <module>
    import blynklib
ImportError: No module named 'blynklib'
>>> 

Of course I am testing on an RPi, not with microPython on ESP… so mileage may vary.

But after spending more time then I would normally, reading/comparing your code with known good code, without such requested actual and full copy/pasted error output, not your interpretation of it, I suspect that you are running into a simple syntax error… AKA not using capitalisation where needed.

image

image

Sorry if I did not follow rules - I changed the library name but:
image

Perhaps the Blynk Python library is not correctly installed?? I have never used it on an ESP, so I can’t help there.

I have tried to install in root and in \lib but the result is the same
Other libraries work just fine

If I use blynklib_mp.mpy, the program runs

Best
Lars

You are following these directions?

Yes - except I didn’t use Ampy but Thonny.to load the library
I have tried to have the Blynk library in root and in \lib but result is the same

Well, sorry, but I must leave this as is for someone else to assist with (assuming there are any ESP/Python/Blynkers active in the forum). I do not want to install Python on my ESPs (I prefer the Arduino IDE way for them) and what I know of past Blynk Python use on the RPI isn’t likely to help.

For old version of Blynk, you have to download these 2 files: blynklib.py and blynklib_mp.py from https://github.com/blynkkk/lib-python, then upload to device.
Change your code
from import blynklib ==> import blynklib_mp as blynklib

BlynkLib.py for Blynk Version 2 ==> https://github.com/vshymanskyy/blynk-library-python