Skip to content

Instantly share code, notes, and snippets.

@plasmon360
Created February 14, 2015 20:02
Show Gist options
  • Save plasmon360/ab314441efec4c7b4298 to your computer and use it in GitHub Desktop.
Save plasmon360/ab314441efec4c7b4298 to your computer and use it in GitHub Desktop.
Python code to read and upload weight information form a weighing scale.
import pigpio
import time
import sys
from datetime import datetime
from collections import Counter
import numpy as np
import plotly.plotly as py
from plotly.graph_objs import *
#command 1 =[0, 0, 0, 0, 0, 0, 1, 1]='0x03'
#command 2 = [0, 1, 0, 0, 0, 1, 0, 0]='0x44'
#command 3 = '0xc0','0xc2','0xc4','0xc6','0xc1' ..for grids 1...5
#data = see seg_to_digit_dict
#command 4 =[1, 0, 0, 0, 1, 0, 1, 1]=0x8B
#power off= [1, 0, 0, 0, 0, 0, 0, 0]=0x80
seg_to_digit_dict={
'0x0':' ' ,
'0xb7':'0' ,
'0x22':'1',
'0xad':'2',
'0xab':'3',
'0x3a':'4',
'0x9b':'5',
'0x9f':'6',
'0xa2':'7',
'0xbf':'8',
'0xbb':'9',
'0xf7':'0.',
'0x62':'1.',
'0xed':'2.',
'0xeb':'3.',
'0x7a':'4.',
'0xdb':'5.',
'0xdf':'6.',
'0xe2':'7.',
'0xff':'8.',
'0xfb':'9.',
'0xf':'o',
'0x8':'-'
}
# These need to be changed.
plotly_user_name = 'temp'
plotly_key = 'temp'
weight_file_path = '/home/pi/Desktop/python_scripts/Weight_log_file.txt'
#
BKJ_MQ=17
GUEST=27
data_pin=25
clock_pin=8
data_level=0
data_list=[]
counter = 0
data_command = False
grid=[]
grid_num = 0
weight = []
weight_ready = False
stable_weight = '0'
def bits_list_to_hex(a):
data_byte='0b'+''.join([str(_) for _ in a])
return hex(int(data_byte,2))
def byte_to_grid(data_byte):
global data_command, grid, grid_num, counter , weight, weight_ready, stable_weight
if data_byte=='0x3':
print 'Woke up. Setting display mode set to 7 grids and 11 segments'
data_command = False
elif data_byte=='0x44':
print 'working in normal mode with fixed addresses and writing data to display mode'
data_command = False
elif data_byte == '0x8B':
print 'Display on. Dimming, pulse width = 10/16'
data_command = False
elif data_byte == '0x80':
print 'Done measuring your weight. Display off. Now sleeping...'
weight_counter=Counter(weight)
try:
weight_counter_max_freq=weight_counter.values().index(max(weight_counter.values())) # Find the number that apeards the most. counter object.values() gives the frequency of the numbers.
stable_weight= weight_counter.keys()[weight_counter_max_freq] #Pick the weight that has the highest frequency. counter object.keys gives the values
except:
stable_weight = None
print ('Your weight is %s lbs' % stable_weight)
weight_ready = True
weight=[]
counter = -1 # This takes care of bad bit that comes when powered on next time
data_command = False
elif data_byte in ['0xc0','0xc2','0xc4','0xc6','0xc1']:
data_command = True
elif data_command == True and data_byte in seg_to_digit_dict.keys():
grid+=seg_to_digit_dict.get(data_byte,'0')
grid_num+=1
if grid_num==5:
print grid
try:
weight.append(float(grid)) # convert the grid data to float
except (TypeError, ValueError) as e: # if special characters come pass the errors
pass
grid=''
grid_num = 0
data_command = False
def cbf(gpio,level,tick):
global data_level, data_list, counter
if gpio == data_pin:
data_level = level
else: # Catch the rising edge
#print(data_level) # recals the last data high or low
if counter > 0: #ignore the first data bit because this represents power on and not a real bit
if len(data_list) < 8: # Make a byte from bits
data_list.append(data_level)
if len(data_list) == 8 : #when a byte is formed
data_list=data_list[::-1]
data_byte=bits_list_to_hex(data_list) # convert it to hex
#print data_byte
byte_to_grid(data_byte) # send the byte to be converted to be grid of characters
data_list=[]
counter+=1
def write_weight_data(weight,user):
print 'Writing to the file'
with open(weight_file_path,'a') as f:
#f.write('#Serial Date User Weight(lbs) \n')
f.write(datetime.now().strftime('%Y-%m-%d %H:%M:%S')+'\t'+user+'\t'+str(weight))
f.write('\n')
time.sleep(.5)
def read_weight_log_file():
print 'Reading the weight log'
time.sleep(0.5)
convertfunc = lambda x: datetime.strptime(x,'%Y-%m-%d %H:%M:%S')
names= ("Date","User","Weight")
data=np.genfromtxt('/home/pi/Desktop/python_scripts/Weight_log_file.txt',delimiter='\t',names=names,dtype=[("Date",'object'),("User",'S5'),("Weight",'<f4')],converters={"Date": convertfunc})
return data
#
def push_data_to_plotly(data,user):
print 'Trying to upload the '+user +' weight data'
py.sign_in(plotly_user_name, plotly_key)
time.sleep(0.5)
weight = Scatter(
name = 'Weight',
x=data['Date'][data['User']==user],
y=data['Weight'][data['User']==user],
mode='lines+markers'
)
plotly_data=[weight]
layout = Layout(title=user+' Weight', xaxis=XAxis(title='Date Time'),yaxis=YAxis(title='Weight (lbs)'))
fig=Figure(data=plotly_data, layout=layout)
plot_url=py.plot(fig,filename=user+'_weight_from_file_upload',world_readable=False, width=1000, height=650)
print user +' weight has been uploaded at '+plot_url
return plot_url
if __name__ == '__main__':
pigpio.start()
pigpio.set_mode(BKJ_MQ,pigpio.INPUT)
pigpio.set_mode(GUEST,pigpio.INPUT)
pigpio.set_mode(clock_pin,pigpio.INPUT)
pigpio.set_mode(data_pin,pigpio.INPUT)
cb1=pigpio.callback(clock_pin,pigpio.RISING_EDGE,cbf)
cb2=pigpio.callback(data_pin,pigpio.EITHER_EDGE,cbf)
try:
while True:
if (weight_ready == True and pigpio.read(BKJ_MQ)):
if (stable_weight > 120 and stable_weight < 180):
print('BKJ weight is %s lbs' % stable_weight)
try:
write_weight_data(stable_weight,'BKJ')
except Exception as e:
print str(e)
data=read_weight_log_file()
push_data_to_plotly(data,'BKJ')
weight_ready = False
elif (stable_weight > 90 and stable_weight < 120):
print('MQ weight is %s lbs' % stable_weight)
write_weight_data(stable_weight,'MQ')
data = read_weight_log_file()
push_data_to_plotly(data,'MQ')
weight_ready = False
else:
print ('BKJ-MQ weight cant be zero or not be atleast 90 lbs. Assuming something wrong. will not upload to plotly')
weight_ready = False
elif (weight_ready == True and pigpio.read(GUEST)):
if (stable_weight > 50 and stable_weight < 500):
print('GUEST weight is %s lbs' % stable_weight)
try:
write_weight_data(stable_weight,'GUEST')
except Exception as e:
print str(e)
data=read_weight_log_file()
push_data_to_plotly(data,'GUEST')
weight_ready = False
else:
print ('Guest weight cant be zero or should be between 50-500lbs. Assuming something wrong. will not upload to plotly')
weight_ready = False
else:
pass
continue
except KeyboardInterrupt:
print 'Good Bye!'
cb1.cancel()
cb2.cancel()
sys.exit()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment