Explorar el Código

added leds class

subDesTagesMitExtraKaese hace 3 años
padre
commit
70d9fb9936
Se han modificado 3 ficheros con 82 adiciones y 59 borrados
  1. 13 4
      config.py
  2. 49 0
      leds.py
  3. 20 55
      main.py

+ 13 - 4
config.py

@@ -2,8 +2,17 @@ import ubinascii
 import machine
 import machine
 
 
 # Default MQTT server to connect to
 # Default MQTT server to connect to
-mqtt_server = "192.168.1.1"
+MQTT_SERVER = "192.168.1.1"
 
 
-client_id = ubinascii.hexlify(machine.unique_id())
-topic_sub = b"Room/rgbBulb/1/command"
-topic_pub = b"Room/rgbBulb/1/state"
+CLIENT_ID = ubinascii.hexlify(machine.unique_id())
+TOPIC_SUB = b"Room/rgbBulb/1/command"
+TOPIC_PUB = b"Room/rgbBulb/1/state"
+
+#LEDs with name, pin and channel
+LED_LIST = [
+  ('R', machine.Pin.PA_05, 0),
+  ('G', machine.Pin.PB_13, 1),
+  ('B', machine.Pin.PB_15, 3),
+  ('C', machine.Pin.PB_16, 2),
+  ('W', machine.Pin.PB_08, 4)
+]

+ 49 - 0
leds.py

@@ -0,0 +1,49 @@
+import time
+from machine import PWM, Pin
+
+from config import LED_LIST
+
+class Leds:
+  def __init__(self):
+    self.led_count = len(LED_LIST)
+    self.pwm = [None] * self.led_count
+    self.vals = [0] * self.led_count
+    self.diff = [0.0] * self.led_count
+    self.stepId = [0] * self.led_count
+    self.steps = 50
+    self.frequency = 800
+  
+  def enable(self, i):
+    if not self.pwm[i]:
+      self.pwm[i] = PWM(Pin(LED_LIST[i][1]), channel=LED_LIST[i][2], freq=self.frequency, duty=0)
+
+  def enableAll(self):
+    for i in range(self.led_count):
+      self.enable(i)
+
+  def disable(self, i):
+    if self.pwm[i]:
+      self.pwm[i].deinit()
+      self.pwm[i] = None
+
+  def disableAll(self):
+    for i in range(self.led_count):
+      self.disable(i)
+
+  def setColor(self, i, val):
+    if not self.pwm[i]:
+      return
+    self.diff[i] = float(self.vals[i] - self.pwm[i].duty()) / (self.steps)
+    self.vals[i] = val
+    self.stepId[i] = 0
+
+  def update(self):
+    for i in range(self.led_count):
+      if not self.pwm[i]:
+        continue
+      if self.stepId[i] > self.steps:
+        self.pwm[i].duty(self.vals[i])
+      else:
+        self.pwm[i].duty(int(self.vals[i] - self.diff[i] * (self.steps - self.stepId[i])))
+        self.stepId[i] += 1
+  

+ 20 - 55
main.py

@@ -7,81 +7,44 @@ import ujson
 import network
 import network
 
 
 from umqttsimple import MQTTClient
 from umqttsimple import MQTTClient
-from config import mqtt_server, client_id, topic_sub, topic_pub
+from config import MQTT_SERVER, CLIENT_ID, TOPIC_SUB, TOPIC_PUB, LED_LIST
+from leds import Leds
 
 
 import gc
 import gc
 gc.collect()
 gc.collect()
 
 
 station = network.WLAN(network.STA_IF)
 station = network.WLAN(network.STA_IF)
-
-vals = {
-  'C': 0,
-  'G': 0,
-  'R': 0,
-  'W': 0,
-  'B': 0
-}
-duration = 50
-pwm = {}
-def initPWM():
-  global pwm
-  pwm = {
-    'C': PWM(Pin(Pin.PB_16), channel=2, freq=800, duty=vals['C']),
-    'G': PWM(Pin(Pin.PB_13), channel=1, freq=800, duty=vals['G']),
-    'R': PWM(Pin(Pin.PA_05), channel=0, freq=800, duty=vals['R']),
-    'W': PWM(Pin(Pin.PB_08), channel=4, freq=800, duty=vals['W']),
-    'B': PWM(Pin(Pin.PB_15), channel=3, freq=800, duty=vals['B'])
-  }
-initPWM()
-
-def fade():
-  global pwm, vals, duration
-  if duration > 2:
-    diff = {}
-    for color in pwm:
-      diff[color] = float(vals[color] - pwm[color].duty()) / (duration-1)
-    for i in range(duration-1, 1, -1):
-      for color in pwm:
-        pwm[color].duty(int(vals[color] - diff[color] * i))
-      time.sleep(0.02)
-  
-  for color in pwm:
-    pwm[color].duty(vals[color])
+leds = Leds()
 
 
 def sub_cb(topic, msg):
 def sub_cb(topic, msg):
-  global pwm, vals, duration
   try:
   try:
     cmd = ujson.loads(str(msg, 'utf-8'))
     cmd = ujson.loads(str(msg, 'utf-8'))
     if 'state' in cmd:
     if 'state' in cmd:
       if cmd['state'] == "OFF":
       if cmd['state'] == "OFF":
-        for color in pwm:
-          pwm[color].deinit()
-        pwm = {}
+        leds.disableAll()
       else:
       else:
-        initPWM()
+        leds.enableAll()
     if 'speed' in cmd:
     if 'speed' in cmd:
-      duration = int(cmd['fade'])
+      leds.steps = int(cmd['fade'])
     if 'color' in cmd:
     if 'color' in cmd:
-      for color in vals:
+      for i, (color, _, _) in enumerate(LED_LIST):
         if color in cmd['color']:
         if color in cmd['color']:
           val = int(cmd['color'][color])
           val = int(cmd['color'][color])
           if val >= 0 and val <= 255:
           if val >= 0 and val <= 255:
-            vals[color] = val
-      fade()
+            leds.setColor(i, val)
     if 'reset' in cmd:
     if 'reset' in cmd:
       machine.reset()
       machine.reset()
     
     
   except Exception as e:
   except Exception as e:
-    client.publish(topic_pub, b"error")
+    client.publish(TOPIC_PUB, b"error")
 
 
 
 
 def connect_and_subscribe():
 def connect_and_subscribe():
-  global client_id, mqtt_server, topic_sub
-  client = MQTTClient(client_id, mqtt_server)
+  client = MQTTClient(CLIENT_ID, MQTT_SERVER)
   client.set_callback(sub_cb)
   client.set_callback(sub_cb)
   client.connect()
   client.connect()
-  client.subscribe(topic_sub)
-  print('Connected to %s MQTT broker, subscribed to %s topic' % (mqtt_server, topic_sub))
+  client.subscribe(TOPIC_SUB)
+  print('Connected to %s MQTT broker, subscribed to %s topic' % (MQTT_SERVER, TOPIC_SUB))
   return client
   return client
 
 
 def restart_and_reconnect():
 def restart_and_reconnect():
@@ -91,7 +54,7 @@ def restart_and_reconnect():
 
 
 try:
 try:
   client = connect_and_subscribe()
   client = connect_and_subscribe()
-  client.set_last_will(topic_pub, b"offline", retain=False, qos=0)
+  client.set_last_will(TOPIC_PUB, b"offline", retain=False, qos=0)
   client.sock.settimeout(10)
   client.sock.settimeout(10)
 except OSError as e:
 except OSError as e:
   print(e)
   print(e)
@@ -103,17 +66,19 @@ counter = 0
 
 
 while True:
 while True:
   try:
   try:
-    client.wait_msg()
+    client.check_msg()
     if (time.time() - last_message) > message_interval:
     if (time.time() - last_message) > message_interval:
       msg = b'online #%d' % counter
       msg = b'online #%d' % counter
-      client.publish(topic_pub, msg)
+      client.publish(TOPIC_PUB, msg)
       last_message = time.time()
       last_message = time.time()
       gc.collect()
       gc.collect()
       counter += 1
       counter += 1
+    leds.update()
+    time.sleep(0.02)
   except OSError as e:
   except OSError as e:
-    client.publish(topic_pub, b"OSError")
+    client.publish(TOPIC_PUB, b"OSError")
     restart_and_reconnect()
     restart_and_reconnect()
   if station.isconnected() == False:
   if station.isconnected() == False:
-    if 'R' in pwm:
-      pwm['R'].duty(60)
+    leds.enable(0)
+    leds.setColor(0, 60)