Moved vibration code into a class

This commit is contained in:
NateSchoolfield 2021-02-05 17:14:25 -08:00
parent f1b9497f0d
commit bca9e148fa
2 changed files with 128 additions and 125 deletions

View File

@ -3,7 +3,9 @@
import time, re, threading import time, re, threading
from bluepy.btle import BTLEDisconnectError from bluepy.btle import BTLEDisconnectError
from miband import miband from miband import miband
import sleepdata, vibrate import sleepdata
from vibrate import Vibrate
@ -13,7 +15,7 @@ mac_filename = 'mac.txt'
maximize_graph = False maximize_graph = False
vibration_settings = { vibration_settings = {
'interval_minutes': 45, 'interval_minutes': 0.1,
'duration_seconds': 5, 'duration_seconds': 5,
'type': 'random' 'type': 'random'
} }
@ -91,7 +93,6 @@ def connect():
try: try:
band = miband(MAC_ADDR, AUTH_KEY, debug=True) band = miband(MAC_ADDR, AUTH_KEY, debug=True)
success = band.initialize() success = band.initialize()
vibrate.band = band
except BTLEDisconnectError: except BTLEDisconnectError:
print(msg.format(timeout)) print(msg.format(timeout))
time.sleep(timeout) time.sleep(timeout)
@ -112,7 +113,7 @@ def start_data_pull():
def start_vibration(): def start_vibration():
while True: while True:
try: try:
vibrate.timed_vibration(vibration_settings) vibration.timed_vibration(vibration_settings)
except BTLEDisconnectError: except BTLEDisconnectError:
print("Vibration thread waiting for band reconnect...") print("Vibration thread waiting for band reconnect...")
time.sleep(1) time.sleep(1)
@ -120,6 +121,7 @@ def start_vibration():
if __name__ == "__main__": if __name__ == "__main__":
connect() connect()
vibration = Vibrate(band)
threading.Thread(target=start_data_pull).start() threading.Thread(target=start_data_pull).start()
threading.Thread(target=start_vibration).start() threading.Thread(target=start_vibration).start()
sleepdata.init_graph(maximize=maximize_graph, graph_displaytime_mins=5) sleepdata.init_graph(maximize=maximize_graph, graph_displaytime_mins=5)

View File

@ -2,8 +2,6 @@ import time
import random import random
import logging import logging
band = None
# Notes: # Notes:
# The miband4 does not (seem to) support different vibration intensities, rather the values sent (2-255) # The miband4 does not (seem to) support different vibration intensities, rather the values sent (2-255)
# represent how long the vibration motor runs. A value of 30 roughly corresponds to 60ms of motor run time. # represent how long the vibration motor runs. A value of 30 roughly corresponds to 60ms of motor run time.
@ -11,142 +9,145 @@ band = None
# Currently "continuous" mode doesn't work, as it doesn't turn off. # Currently "continuous" mode doesn't work, as it doesn't turn off.
# This will be fixed shortly. # This will be fixed shortly.
class Vibrate():
vibrate_band = None
vibration_log = None
def __init__(self, band):
self.vibrate_band = band
if __name__ == 'vibrate':
FORMAT = '%(asctime)-15s %(name)s (%(levelname)s) > %(message)s' FORMAT = '%(asctime)-15s %(name)s (%(levelname)s) > %(message)s'
logging.basicConfig(format=FORMAT) logging.basicConfig(format=FORMAT)
vibration_log_level = logging.INFO vibration_log_level = logging.INFO
vibration_log = logging.getLogger(__name__) self.vibration_log = logging.getLogger(__name__)
vibration_log.setLevel(vibration_log_level) self.vibration_log.setLevel(vibration_log_level)
def timed_vibration(self, settings):
interval_minutes = settings['interval_minutes']
duration_seconds = settings['duration_seconds']
type = settings['type']
buzz_timer = time.time()
tick_time = time.time()
buzz_delay = interval_minutes * 60
self.vibration_log.info("Starting vibration timer: {} minutes".format(interval_minutes))
if type not in ['random', 'pattern', 'rolling', 'continuous']:
self.vibration_log.warn("Invalid or no vibration type specified: {}".format(type))
self.vibration_log.warn("Must be one of these: random, pattern, rolling, continuous")
return
while True:
elapsed_time = tick_time - buzz_timer
if elapsed_time >= buzz_delay:
print("Buzz timer expired, buzzing")
if type == 'random':
self.vibrate_random(duration_seconds)
elif type == 'pattern':
self.vibrate_pattern(duration_seconds)
elif type == 'rolling':
self.vibrate_rolling(duration_seconds)
elif type == 'continuous':
self.vibrate_continuous(duration_seconds)
buzz_timer = tick_time
else:
tick_time = time.time()
time.sleep(0.5)
def timed_vibration(settings): def generate_random_vibration_pattern(self, pulse_count):
interval_minutes = settings['interval_minutes'] #pulse_duration_range and pulse_interval_range_ms are arbitrary
duration_seconds = settings['duration_seconds'] pulse_duration_range = {
type = settings['type'] 'low': 80,
'high': 120
buzz_timer = time.time() }
tick_time = time.time() pulse_interval_range_ms = {
buzz_delay = interval_minutes * 60 'low': 100,
'high': 800
}
vibration_log.info("Starting vibration timer: {} minutes".format(interval_minutes)) output_pulse_pattern = []
for _ in range(pulse_count):
if type not in ['random', 'pattern', 'rolling', 'continuous']: pulse_duration = random.randrange(pulse_duration_range['low'], pulse_duration_range['high'])
vibration_log.warn("Invalid or no vibration type specified: {}".format(type)) pulse_interval = random.randrange(pulse_interval_range_ms['low'], pulse_interval_range_ms['high'])/1000
vibration_log.warn("Must be one of these: random, pattern, rolling, continuous") output_pulse_pattern.append([pulse_duration, pulse_interval])
return return output_pulse_pattern
while True:
elapsed_time = tick_time - buzz_timer
if elapsed_time >= buzz_delay:
print("Buzz timer expired, buzzing")
if type == 'random':
vibrate_random(duration_seconds)
elif type == 'pattern':
vibrate_pattern(duration_seconds)
elif type == 'rolling':
vibrate_rolling(duration_seconds)
elif type == 'continuous':
vibrate_continuous(duration_seconds)
buzz_timer = tick_time
else:
tick_time = time.time()
time.sleep(0.5)
def generate_random_vibration_pattern(pulse_count): def vibrate_random(self, duration_seconds):
#pulse_duration_range and pulse_interval_range_ms are arbitrary print("Sending random vibration...")
pulse_duration_range = { duration_start = time.time()
'low': 80,
'high': 120
}
pulse_interval_range_ms = {
'low': 100,
'high': 800
}
output_pulse_pattern = [] pattern_length = 20 #This value is arbitrary
for _ in range(pulse_count):
pulse_duration = random.randrange(pulse_duration_range['low'], pulse_duration_range['high']) pulse_pattern = self.generate_random_vibration_pattern(pattern_length)
pulse_interval = random.randrange(pulse_interval_range_ms['low'], pulse_interval_range_ms['high'])/1000
output_pulse_pattern.append([pulse_duration, pulse_interval]) while True:
return output_pulse_pattern if (time.time() - duration_start) >= duration_seconds:
print ("Stopping vibration")
self.vibrate_band.vibrate(0)
break
else:
for pattern in pulse_pattern:
if (time.time() - duration_start) >= duration_seconds:
break
vibrate_ms = pattern[0]
vibro_delay = pattern[1]
self.vibrate_band.vibrate(vibrate_ms)
time.sleep(vibro_delay)
def vibrate_random(duration_seconds): def vibrate_pattern(self, duration_seconds):
print("Sending random vibration...") print("Sending vibration...")
duration_start = time.time() duration_start = time.time()
pattern_length = 20 #This value is arbitrary #This pattern is an example.
pulse_pattern = [[30, 0.01], [60, 0.01], [90, 0.01], [120, 0.01], [150, 0.01], [180, 0.01]]
pulse_pattern = generate_random_vibration_pattern(pattern_length) while True:
if (time.time() - duration_start) >= duration_seconds:
while True: print ("Stopping vibration")
if (time.time() - duration_start) >= duration_seconds: self.vibrate_band.vibrate(0)
print ("Stopping vibration") break
band.vibrate(0) else:
break for pattern in pulse_pattern:
else: if (time.time() - duration_start) >= duration_seconds:
for pattern in pulse_pattern: break
if (time.time() - duration_start) >= duration_seconds: vibrate_ms = pattern[0]
break vibro_delay = pattern[1]
vibrate_ms = pattern[0] self.vibrate_band.vibrate(vibrate_ms)
vibro_delay = pattern[1] time.sleep(vibro_delay)
band.vibrate(vibrate_ms)
time.sleep(vibro_delay)
def vibrate_pattern(duration_seconds): def vibrate_rolling(self, duration_seconds):
print("Sending vibration...") print("Sending rolling vibration...")
duration_start = time.time()
#This pattern is an example. duration_start = time.time()
pulse_pattern = [[30, 0.01], [60, 0.01], [90, 0.01], [120, 0.01], [150, 0.01], [180, 0.01]]
while True:
if (time.time() - duration_start) >= duration_seconds:
print ("Stopping vibration")
self.vibrate_band.vibrate(0)
break
else:
for x in range(10):
for x in range(20, 40, 1):
self.vibrate_band.vibrate(x)
for x in range(40, 20, -1):
self.vibrate_band.vibrate(x)
while True: def vibrate_continuous(self, duration_seconds):
if (time.time() - duration_start) >= duration_seconds: #Currently broken, still working on this bit.
print ("Stopping vibration") print("Sending continuous vibration...")
band.vibrate(0)
break
else:
for pattern in pulse_pattern:
if (time.time() - duration_start) >= duration_seconds:
break
vibrate_ms = pattern[0]
vibro_delay = pattern[1]
band.vibrate(vibrate_ms)
time.sleep(vibro_delay)
duration_start = time.time()
def vibrate_rolling(duration_seconds):
print("Sending rolling vibration...") while True:
if (time.time() - duration_start) >= duration_seconds:
duration_start = time.time() print ("Stopping vibration")
self.vibrate_band.vibrate(0)
while True: break
if (time.time() - duration_start) >= duration_seconds: else:
print ("Stopping vibration") self.vibrate_band.vibrate(1)
band.vibrate(0)
break
else:
for x in range(10):
for x in range(20, 40, 1):
band.vibrate(x)
for x in range(40, 20, -1):
band.vibrate(x)
def vibrate_continuous(duration_seconds):
#Currently broken, still working on this bit.
print("Sending continuous vibration...")
duration_start = time.time()
while True:
if (time.time() - duration_start) >= duration_seconds:
print ("Stopping vibration")
band.vibrate(0)
break
else:
band.vibrate(1)