Compare commits

...
27 Commits
Author SHA1 Message Date
adligeerik 7b84b2e84b Merge branch 'master' of https://git.elab.kth.se/marek/Twitch-grabs-candy 2018-11-25 08:47:43 +01:00
adligeerik 073f1f3805 new pictures 2018-11-25 08:47:17 +01:00
davide 94f2e8c34e Merge branch 'master' of git.elab.kth.se:marek/Twitch-grabs-candy 2018-11-25 08:26:37 +01:00
Wilhelm Westermark be72ed2dfd 3D models for scale rig 2018-11-25 08:26:37 +01:00
davide 2e4a3e9e07 Fixed order placing 2018-11-25 08:26:25 +01:00
davide 3500e29157 Merge branch 'master' of git.elab.kth.se:marek/Twitch-grabs-candy 2018-11-25 00:02:39 +01:00
davide 6c45e79137 Parsing new order 2018-11-25 00:02:33 +01:00
davide da94ed3e15 Added candy count code 2018-11-25 00:02:15 +01:00
Wilhelm Westermark 46801a586f Final fast code for the scale 2018-11-24 23:53:50 +01:00
Wilhelm Westermark ccaee0bddd Remove faulty file 2018-11-24 23:42:10 +01:00
Wilhelm Westermark 7d22bc3b86 Updated for mobile 2018-11-24 23:41:36 +01:00
marek ea4b383e66 fixed the numeric picker 2018-11-25 00:01:11 +02:00
davide a789310c2d Merge branch 'master' of git.elab.kth.se:marek/Twitch-grabs-candy 2018-11-24 22:15:50 +01:00
marek 86820ebfc6 fixed windows 2018-11-24 23:13:55 +02:00
davide 3ed89ee6dc Some changes 2018-11-24 21:54:49 +01:00
marek 9b0f67b5ef order site 1 2018-11-24 22:52:47 +02:00
adligeerik 54833c1c9d working chat and robot contoller 2018-11-24 21:11:04 +01:00
pk23 95892796ed Merged the chat parser with the robot control 2018-11-24 21:23:19 +02:00
pk23 87449e287e Merge branch 'master' of https://git.elab.kth.se/marek/Twitch-grabs-candy 2018-11-24 21:18:28 +02:00
pk23 0d7a234a25 move function has been updated with the chat parser 2018-11-24 21:16:16 +02:00
pk23 d0717ec157 Merged the Chat parser with the robot arm control. 2018-11-24 20:59:09 +02:00
davide 071236bc0e Merge branch 'master' of git.elab.kth.se:marek/Twitch-grabs-candy 2018-11-24 19:54:01 +01:00
davide c1f64d6f4c Some working overlay action 2018-11-24 19:53:07 +01:00
Wilhelm Westermark 974894f1ee Average code on serial available 2018-11-24 19:51:04 +01:00
adligeerik 9ee108ee57 key words 2018-11-24 19:07:40 +01:00
adligeerik 78edcbd44b Merge branch 'master' of https://git.elab.kth.se/marek/Twitch-grabs-candy 2018-11-24 18:58:30 +01:00
adligeerik da0d5556a8 test 2018-11-24 18:58:22 +01:00
19 changed files with 1054 additions and 81 deletions
Binary file not shown.
+114 -6
View File
@@ -2,6 +2,12 @@ import time
import threading import threading
import DobotDllType as dType import DobotDllType as dType
import json
import socket, select
import re
from time import sleep
""" """
Six actuators: Six actuators:
linear rail linear rail
@@ -202,7 +208,7 @@ def adjustSpeed(motor, adjustment):
global nowTime, stopTime, currentMotor, speed, motorcfg, movement_time, max_speed, max_movement_time global nowTime, stopTime, currentMotor, speed, motorcfg, movement_time, max_speed, max_movement_time
if currentMotor==motor: if currentMotor==motor:
if (adjustment>0 and speed>0) or (adjustment<0 and speed<0):= if (adjustment>0 and speed>0) or (adjustment<0 and speed<0):
speed += adjustment * 1-(abs(speed)/max_speed) speed += adjustment * 1-(abs(speed)/max_speed)
else: else:
stopMotorFunctions() stopMotorFunctions()
@@ -244,16 +250,22 @@ def updateLoop():
def rt(): def rt():
adjustSpeed(1, 5)
def lt():
adjustSpeed(1, -5) adjustSpeed(1, -5)
def up(): def lt():
adjustSpeed(1, 5)
def bc():
adjustSpeed(2, -5)
def fw():
adjustSpeed(2, 5) adjustSpeed(2, 5)
def up():
adjustSpeed(3, -5)
def dn(): def dn():
adjustSpeed(2, -5) adjustSpeed(3, 5)
def lr(): def lr():
adjustSpeed(4, 10) adjustSpeed(4, 10)
@@ -315,4 +327,100 @@ def stop():
with open('twitch_key.json', 'rb') as json_data:
data = json.load(json_data)
primary_stream_key = data["primary_stream_key"]
oauth_key = data["oauth_key"]# bytes('oauth:gcpsl3csq85rf3lk8c1ijzer8deuat', "utf8")
print(primary_stream_key)
print(oauth_key)
HOST = "irc.chat.twitch.tv"
PORT = 6667
PASS = oauth_key
NICK = "TwitchGrabsCandy"
CHAN = "#twitchgrabscandy"
s = socket.socket()
s.connect((HOST, PORT))
s.send("PASS {}\r\n".format(PASS).encode("utf-8"))
s.send("NICK {}\r\n".format(NICK).encode("utf-8"))
s.send("JOIN {}\r\n".format(CHAN).encode("utf-8"))
s.setblocking(0)
queue = []
while True:
response = ""
ready = select.select([s], [], [], 0.1)
if ready[0]:
print("Trying")
response = s.recv(1024).decode("utf-8") # blocking
# print(response)
if re.search("up", response) != None:
queue = queue + ["up"]
if re.search("down", response) != None:
queue = queue + ["down"]
if re.search("go left", response) != None:
queue = queue + ["gleft"]
if re.search("go right", response) != None:
queue = queue + ["gright"]
if re.search("turn left", response) != None:
queue = queue + ["tleft"]
if re.search("turn right", response) != None:
queue = queue + ["tright"]
if re.search("forward", response) != None:
queue = queue + ["forward"]
if re.search("back", response) != None:
queue = queue + ["back"]
if re.search("grasp", response) != None:
queue = queue + ["grasp"]
if re.search("drop", response) != None:
queue = queue + ["drop"]
# checking the motion that is first in the FIFO queue
if len(queue):
if queue[0] == "up":
up()
elif queue[0] == "down":
dn()
elif queue[0] == "gleft":
ll()
elif queue[0] == "gright":
lr()
elif queue[0] == "tleft":
lt()
elif queue[0] == "tright":
rt()
elif queue[0] == "forward":
fw()
elif queue[0] == "back":
bc()
elif queue[0] == "grasp":
grab()
elif queue[0] == "drop":
drop()
else:
print("Something is TERRIBLY wrong!")
# removing the first item from queue
queue = queue[1:]
sleep(1)
+412
View File
@@ -0,0 +1,412 @@
import time
import threading
import DobotDllType as dType
import json
import socket, select
import re
from time import sleep
"""
Six actuators:
linear rail
base rotation
rear arm
forarm
gripperrotation
gripper
First five takes argument 1 or -1 (direction)
Example:
#initialisation
c = Candybot()
c.linear(1) # move linear in positive direction
c.gripp() # gripp candy
c.letgo() # let go of candy
c.stopcmp() # stoop compressor
c.panic() # stops everything
"""
class Candybot:
def __init__(self):
self.jointspeed = 100
self.lastjointspeed = 100
self.linearspeed = 100
self.lastleinearspeed = 100
return
CON_STR = {
dType.DobotConnect.DobotConnect_NoError: "DobotConnect_NoError",
dType.DobotConnect.DobotConnect_NotFound: "DobotConnect_NotFound",
dType.DobotConnect.DobotConnect_Occupied: "DobotConnect_Occupied"}
#Load Dll
self.api = dType.load()
#Connect Dobot
state = dType.ConnectDobot(self.api, "", 115200)[0]
print("Connect status:",CON_STR[state])
if (state == dType.DobotConnect.DobotConnect_NoError):
#Clean Command Queued
dType.SetQueuedCmdClear(self.api)
#Async Motion Params Setting
dType.SetHOMEParams(self.api, 250, 0, 50, 0, isQueued = 1)
dType.SetJOGJointParams(self.api, 2, 200, 2, 200, 2, 200, 2, 200, isQueued = 1)
dType.SetJOGCommonParams(self.api, 100, 100, isQueued = 1)
#linear rail
dType.SetDeviceWithL(self.api, 1)
dType.SetJOGLParams(self.api, 200, 200, isQueued=0)
#Async Home
dType.SetHOMECmd(self.api, temp = 0, isQueued = 1)
def disconnect(self):
#Disconnect Dobot
dType.DisconnectDobot(self.api)
def base(self, direction):
if direction == 1:
dType.SetJOGCmd(self.api,1,1)
elif direction == -1:
dType.SetJOGCmd(self.api,1,2)
else :
return
threading.Timer(0.1,self.stop).start()
#dType.SetWAITCmd(self.api, 1, isQueued=0)
#dType.SetJOGCmd(self.api, 1, 0)
def rearArm(self, direction):
if direction == 1:
dType.SetJOGCmd(self.api,1,3)
elif direction == -1:
dType.SetJOGCmd(self.api,1,4)
else :
return
#dType.SetWAITCmd(self.api, 1, isQueued=0)
#dType.SetJOGCmd(self.api, 1, 0)
threading.Timer(0.1,self.stop).start()
def forearm(self, direction):
if direction == 1:
dType.SetJOGCmd(self.api,1,5)
elif direction == -1:
dType.SetJOGCmd(self.api,1,6)
else :
return
#dType.SetWAITCmd(self.api, 1, isQueued=0)
#dType.SetJOGCmd(self.api, 1, 0)
threading.Timer(0.1,self.stop).start()
def gripperRotation(self, direction):
if direction == 1:
dType.SetJOGCmd(self.api,1,7)
elif direction == -1:
dType.SetJOGCmd(self.api,1,8)
else :
return
#dType.SetWAITCmd(self.api, 1, isQueued=0)
#dType.SetJOGCmd(self.api, 1, 0)
threading.Timer(0.1,self.stop).start()
def linear(self, direction):
if direction == 1:
dType.SetJOGCmd(self.api,1,9)
elif direction == -1:
dType.SetJOGCmd(self.api,1,10)
else :
return
#dType.SetWAITCmd(self.api, 1, isQueued=0)
#dType.SetJOGCmd(self.api, 1, 0)
self.lint = threading.Timer(0.2,self.stop)
self.lint.start()
def gripp(self):
print("gripping\n")
#dType.SetEndEffectorGripper(self.api, 1, 1, isQueued=0)
def letgo(self):
print("drops\n")
#dType.SetEndEffectorGripper(self.api, 1, 0, isQueued=0)
def stop(self):
print("stops\n")
#dType.SetJOGCmd(self.api, 1, 0)
def stopcmp(self):
print("stops compressor\n")
dType.SetEndEffectorGripper(self.api, 0, 0, isQueued=0)
def panic(self):
dType.SetQueuedCmdForceStopExec(self.api)
def getCurrentCmd(self):
return dType.GetQueuedCmdCurrentIndex(self.api)
def JOGtest(self):
dType.SetJOGCmd(self.api,1,1)
dType.SetJOGCmd(self.api,1,9)
def JOGtest2(self):
dType.SetJOGLParams(self.api, 100, 200, isQueued=0)
dType.SetJOGCmd(self.api,1,9)
time.sleep(1)
for speed in range(100,10,-10):
time.sleep(0.3)
dType.SetJOGLParams(self.api, speed, 200, isQueued=0)
def setparams(self, name, speed):
lookup = {'base' : 0, 'reararm' : 1, 'forearm' : 2, 'gripperroation' :3}
if name == 'rail':
print("Change speed rail " + str(speed) +"\n" )
#dType.SetJOGLParams(self.api, speed, 200, isQueued=0)
else:
speeds = [0,0,0,0]
speeds[lookup[name]] = speed
print("change speed " + name + str(speed))
#dType.SetJOGJointParams(self.api, speeds[0], 200, speeds[1], 200, speeds[2], 200, speeds[3], 200, isQueued = 1)
def setJOGcmd(self, cmd):
print("Joint "+ str(cmd) + "is moving \n")
#dType.SetJOGCmd(self.api,1,cmd)
candy = Candybot()
startTime = time.time()
nowTime = 0
currentMotor = 0
motorcfg = [0] * 10
motorcfg[1] = {"name" : 'base' , "positive":1, "negative":2, 'speedslot':2}
motorcfg[2] = {"name" : 'reararm' ,"positive":3, "negative":4, 'speedslot':4}
motorcfg[3] = {"name" : 'forearm' ,"positive":5, "negative":6, 'speedslot':6}
motorcfg[4] = {"name" : 'rail' ,"positive":9, "negative":10, 'speedslot':1}
friction = 0.95
movement_time = 3
max_movement_time = 5
min_speed = 1
max_speed = 100
speed = 0
stopTime = 0
isRunning = False
def adjustSpeed(motor, adjustment):
global nowTime, stopTime, currentMotor, speed, motorcfg, movement_time, max_speed, max_movement_time
if currentMotor==motor:
if (adjustment>0 and speed>0) or (adjustment<0 and speed<0):
speed += adjustment * (abs(speed)/max_speed)
else:
stopMotorFunctions()
stopTime += movement_time/2 * max_movement_time/(stopTime - nowTime)
else:
currentMotor = motor
speed = adjustment
stopTime = nowTime + movement_time
if(speed>0):
candy.setJOGcmd(motorcfg[currentMotor]['positive'])
#print("JOG command {}".format(motorcfg[currentMotor]['positive']))
else:
candy.setJOGcmd(motorcfg[currentMotor]['negative'])
# print("JOG command {}".format(motorcfg[currentMotor]['negative']))
def stopMotorFunctions():
global currentMotor, speed
currentMotor = 0
speed = 0
candy.stop()
def updateLoop():
global nowTime, stopTime, currentMotor, speed, friction, min_speed, motorcfg
nowTime = (time.time() - startTime)
threading.Timer(1, updateLoop).start()
if currentMotor != 0:
if nowTime > stopTime:
stopMotorFunctions()
return
else:
speed *= friction
if abs(speed) < min_speed:
stopMotorFunctions()
return
candy.setparams(motorcfg[currentMotor]['name'], abs(speed))
#print("JOG parameter {} to {}".format( motorcfg[currentMotor]['speedslot'], abs(speed)) )
def rt():
adjustSpeed(1, 5)
print("TURNING RIGHT!")
def lt():
adjustSpeed(1, -5)
print("TURNING LEFT!")
def fw():
adjustSpeed(2, 5)
print("GOING FORWARD!")
def bc():
adjustSpeed(2, -5)
print("GOING BACK!")
def up():
adjustSpeed(3, 5)
print("UP!")
def dn():
adjustSpeed(3, -5)
print("DOWN!")
def lr():
adjustSpeed(4, 10)
print("GOING RIGHT!")
def ll():
adjustSpeed(4, -10)
print("GOING LEFT!")
updateLoop()
def stopCmp():
candy.stopcmp()
def grab():
candy.gripp()
print("GRASP!")
def drop():
candy.letgo()
print("DROPPING!")
def stop():
candy.panic()
############################### Chat Parser Section ###############################
with open('/Users/pawel/Documents/Junction2018/twitch_key.json', 'rb') as json_data:
data = json.load(json_data)
primary_stream_key = data["primary_stream_key"]
oauth_key = data["oauth_key"]# bytes('oauth:gcpsl3csq85rf3lk8c1ijzer8deuat', "utf8")
print(primary_stream_key)
print(oauth_key)
HOST = "irc.chat.twitch.tv"
PORT = 6667
PASS = oauth_key
NICK = "TwitchGrabsCandy"
CHAN = "#twitchgrabscandy"
s = socket.socket()
s.connect((HOST, PORT))
s.send("PASS {}\r\n".format(PASS).encode("utf-8"))
s.send("NICK {}\r\n".format(NICK).encode("utf-8"))
s.send("JOIN {}\r\n".format(CHAN).encode("utf-8"))
s.setblocking(0)
queue = []
while True:
response = ""
ready = select.select([s], [], [], 0.1)
if ready[0]:
print("Trying")
response = s.recv(1024).decode("utf-8") # blocking
# print(response)
if re.search("up", response) != None:
queue = queue + ["up"]
if re.search("down", response) != None:
queue = queue + ["down"]
if re.search("go left", response) != None:
queue = queue + ["gleft"]
if re.search("go right", response) != None:
queue = queue + ["gright"]
if re.search("turn left", response) != None:
queue = queue + ["tleft"]
if re.search("turn right", response) != None:
queue = queue + ["tright"]
if re.search("forward", response) != None:
queue = queue + ["forward"]
if re.search("back", response) != None:
queue = queue + ["back"]
if re.search("grasp", response) != None:
queue = queue + ["grasp"]
if re.search("drop", response) != None:
queue = queue + ["drop"]
# checking the motion that is first in the FIFO queue
if len(queue):
if queue[0] == "up":
up()
elif queue[0] == "down":
dn()
elif queue[0] == "gleft":
ll()
elif queue[0] == "gright":
lr()
elif queue[0] == "tleft":
lt()
elif queue[0] == "tright":
rt()
elif queue[0] == "forward":
fw()
elif queue[0] == "back":
bc()
elif queue[0] == "grasp":
grab()
elif queue[0] == "drop":
drop()
else:
print("Something is TERRIBLY wrong!")
# removing the first item from queue
queue = queue[1:]
sleep(1)
+133 -45
View File
@@ -2,6 +2,11 @@ import time
import threading import threading
import DobotDllType as dType import DobotDllType as dType
import json
import socket, select
import re
from time import sleep
""" """
Six actuators: Six actuators:
linear rail linear rail
@@ -30,6 +35,7 @@ class Candybot:
self.linearspeed = 100 self.linearspeed = 100
self.lastleinearspeed = 100 self.lastleinearspeed = 100
return
CON_STR = { CON_STR = {
dType.DobotConnect.DobotConnect_NoError: "DobotConnect_NoError", dType.DobotConnect.DobotConnect_NoError: "DobotConnect_NoError",
@@ -136,7 +142,7 @@ class Candybot:
def letgo(self): def letgo(self):
print("drops\n") print("drops\n")
dType.SetEndEffectorGripper(self.api, 1, 0, isQueued=0) #dType.SetEndEffectorGripper(self.api, 1, 0, isQueued=0)
def stop(self): def stop(self):
print("stops\n") print("stops\n")
@@ -168,17 +174,18 @@ class Candybot:
def setparams(self, name, speed): def setparams(self, name, speed):
lookup = {'base' : 0, 'reararm' : 1, 'forearm' : 2, 'gripperroation' :3} lookup = {'base' : 0, 'reararm' : 1, 'forearm' : 2, 'gripperroation' :3}
if name == 'rail': if name == 'rail':
print("Change speed rail %d\n", speed) print("Change speed rail " + str(speed) +"\n" )
#dType.SetJOGLParams(self.api, speed, 200, isQueued=0) #dType.SetJOGLParams(self.api, speed, 200, isQueued=0)
else: else:
speeds = [0,0,0,0] speeds = [0,0,0,0]
speeds[lookup[name]] = speed speeds[lookup[name]] = speed
print("change speed" + name + "%d\n",speed) print("change speed " + name + str(speed))
#dType.SetJOGJointParams(self.api, speeds[0], 200, speeds[1], 200, speeds[2], 200, speeds[3], 200, isQueued = 1) #dType.SetJOGJointParams(self.api, speeds[0], 200, speeds[1], 200, speeds[2], 200, speeds[3], 200, isQueued = 1)
def setJOGcmd(self, cmd): def setJOGcmd(self, cmd):
dType.SetJOGCmd(self.api,1,cmd) print("Joint "+ str(cmd) + "is moving \n")
#dType.SetJOGCmd(self.api,1,cmd)
candy = Candybot() candy = Candybot()
@@ -251,73 +258,154 @@ def updateLoop():
def rt(): def rt():
adjustSpeed(1, 5) adjustSpeed(1, 5)
print("TURNING RIGHT!")
def lt(): def lt():
adjustSpeed(1, -5) adjustSpeed(1, -5)
print("TURNING LEFT!")
def fw():
adjustSpeed(2, 5)
print("GOING FORWARD!")
def bc():
adjustSpeed(2, -5)
print("GOING BACK!")
def up(): def up():
adjustSpeed(2, 5) adjustSpeed(3, 5)
print("UP!")
def dn(): def dn():
adjustSpeed(2, -5) adjustSpeed(3, -5)
print("DOWN!")
def lr(): def lr():
adjustSpeed(4, 10) adjustSpeed(4, 10)
print("GOING RIGHT!")
def ll(): def ll():
adjustSpeed(4, -10) adjustSpeed(4, -10)
print("GOING LEFT!")
updateLoop() updateLoop()
#
#c = Candybot()
#
#
#def slide_left():
# c.linear(-1)
#
#def slide_right():
# c.linear(1)
#
#def rotate_left():
# c.base(-1)
#
#def rotate_right():
# c.base(1)
#
#def forward():
# c.forearm(1)
#
#def back():
# c.forearm(-1)
#
#def up():
# c.rearArm(1)
#
#def down():
# c.rearArm(-1)
#
def stopCmp(): def stopCmp():
candy.stopcmp() candy.stopcmp()
def grab(): def grab():
candy.gripp() candy.gripp()
# c.stopcmp() print("GRASP!")
#
def drop(): def drop():
candy.letgo() candy.letgo()
# c.stopcmp() print("DROPPING!")
#
def stop(): def stop():
candy.panic() candy.panic()
#
#def getCurrentCmd():
# return c.getCurrentCmd() ############################### Chat Parser Section ###############################
#
#def updateLinearSpeed(): with open('/Users/pawel/Documents/Junction2018/twitch_key.json', 'rb') as json_data:
# pass data = json.load(json_data)
# primary_stream_key = data["primary_stream_key"]
oauth_key = data["oauth_key"]# bytes('oauth:gcpsl3csq85rf3lk8c1ijzer8deuat', "utf8")
print(primary_stream_key)
print(oauth_key)
HOST = "irc.chat.twitch.tv"
PORT = 6667
PASS = oauth_key
NICK = "TwitchGrabsCandy"
CHAN = "#twitchgrabscandy"
s = socket.socket()
s.connect((HOST, PORT))
s.send("PASS {}\r\n".format(PASS).encode("utf-8"))
s.send("NICK {}\r\n".format(NICK).encode("utf-8"))
s.send("JOIN {}\r\n".format(CHAN).encode("utf-8"))
s.setblocking(0)
queue = []
while True:
response = ""
ready = select.select([s], [], [], 0.1)
if ready[0]:
print("Trying")
response = s.recv(1024).decode("utf-8") # blocking
# print(response)
if re.search("up", response) != None:
queue = queue + ["up"]
if re.search("down", response) != None:
queue = queue + ["down"]
if re.search("go left", response) != None:
queue = queue + ["gleft"]
if re.search("go right", response) != None:
queue = queue + ["gright"]
if re.search("turn left", response) != None:
queue = queue + ["tleft"]
if re.search("turn right", response) != None:
queue = queue + ["tright"]
if re.search("forward", response) != None:
queue = queue + ["forward"]
if re.search("back", response) != None:
queue = queue + ["back"]
if re.search("grasp", response) != None:
queue = queue + ["grasp"]
if re.search("drop", response) != None:
queue = queue + ["drop"]
# checking the motion that is first in the FIFO queue
if len(queue):
if queue[0] == "up":
up()
elif queue[0] == "down":
dn()
elif queue[0] == "gleft":
ll()
elif queue[0] == "gright":
lr()
elif queue[0] == "tleft":
lt()
elif queue[0] == "tright":
rt()
elif queue[0] == "forward":
fw()
elif queue[0] == "back":
bc()
elif queue[0] == "grasp":
grab()
elif queue[0] == "drop":
drop()
else:
print("Something is TERRIBLY wrong!")
# removing the first item from queue
queue = queue[1:]
sleep(1)
+45
View File
@@ -0,0 +1,45 @@
import json
import requests
from flask import Flask
from flask import render_template, request, Response
import xmlrpc.client
s = xmlrpc.client.ServerProxy('http://localhost:8000')
app = Flask(__name__)
@app.route('/', strict_slashes=False)
def index():
return render_template('index.html')
@app.route('/order', methods=['POST'])
def order():
candy1 = int(request.form['candy1'])
candy2 = int(request.form['candy2'])
candy3 = int(request.form['candy3'])
candy4 = int(request.form['candy4'])
print ("test {} {} {} {} ".format(candy1, candy2, candy3, candy4))
params = []
s = {}
s['img_idx'] = 0
s['loaded'] = 0
s['required'] = candy1
test_candy_stat.append(s)
s['img_idx'] = 1
s['loaded'] = 0
s['required'] = candy2
test_candy_stat.append(s)
s['img_idx'] = 2
s['loaded'] = 0
s['required'] = candy3
test_candy_stat.append(s)
s['img_idx'] = 3
s['loaded'] = 0
s['required'] = candy4
test_candy_stat.append(s)
s.new_order(params)
return '{"status":"ok"}'
if __name__ == '__main__':
app.run('0.0.0.0')
+61
View File
@@ -0,0 +1,61 @@
$(document).ready(function(){
var quantitiy=0;
$('.quantity-right-plus').click(function(e){
// Stop acting like a button
e.preventDefault();
// Get the field name
var quantity = parseInt( $(this).parent().siblings('input').val() ) ;
// If is not undefined
// $('#quantity').val(quantity + 1);
$(this).parent().siblings('input').val(quantity + 1)
// Increment
});
$('.quantity-left-minus').click(function(e){
// Stop acting like a button
e.preventDefault();
// Get the field name
var quantity = parseInt( $(this).parent().siblings('input').val() ) ;
// If is not undefined
// Increment
if(quantity>0){
$(this).parent().siblings('input').val(quantity - 1);
}
});
});
function submitOrder(){
var data = new FormData();
data.append('candy1', $('#candy1').val());
data.append('candy2', $('#candy2').val());
data.append('candy3', $('#candy3').val());
data.append('candy4', $('#candy4').val());
$.ajax({
url: 'order',
type: 'POST',
cache: false,
data: data,
contentType: false,
processData: false,
success: function() {
alert("ok")
},
fail: function() {
alert("not ok")
},
});
}
View File
+98
View File
@@ -0,0 +1,98 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Alepa Twitch Grabs Candy</title>
<script src="//code.jquery.com/jquery-1.11.1.min.js"></script>
<script type="text/javascript" src="{{url_for('static', filename='picker.js')}}"></script>
<link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.0/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">
<script src="//maxcdn.bootstrapcdn.com/bootstrap/3.3.0/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<div class="row">
<h2>Choose your sweets with a wicked system made out of an awesome humanless deployment process</h2>
<div class="col-lg-2">
Tasty treats
<div class="input-group">
<span class="input-group-btn">
<button type="button" class="quantity-left-minus btn btn-danger btn-number" data-type="minus" data-field="">
<span class="glyphicon glyphicon-minus"></span>
</button>
</span>
<input type="text" id="candy1" name="quantity" class="form-control input-number" value="0" min="1" max="20">
<span class="input-group-btn">
<button type="button" class="quantity-right-plus btn btn-success btn-number" data-type="plus" data-field="">
<span class="glyphicon glyphicon-plus"></span>
</button>
</span>
</div>
</div>
<div class="col-lg-2">
Sweet snacks
<div class="input-group">
<span class="input-group-btn">
<button type="button" class="quantity-left-minus btn btn-danger btn-number" data-type="minus" data-field="">
<span class="glyphicon glyphicon-minus"></span>
</button>
</span>
<input type="text" id="candy2" name="quantity" class="form-control input-number" value="0" min="1" max="20">
<span class="input-group-btn">
<button type="button" class="quantity-right-plus btn btn-success btn-number" data-type="plus" data-field="">
<span class="glyphicon glyphicon-plus"></span>
</button>
</span>
</div>
</div>
<div class="col-lg-2">
Chocolaty candy
<div class="input-group">
<span class="input-group-btn">
<button type="button" class="quantity-left-minus btn btn-danger btn-number" data-type="minus" data-field="">
<span class="glyphicon glyphicon-minus"></span>
</button>
</span>
<input type="text" id="candy3" name="quantity" class="form-control input-number" value="0" min="0" max="20">
<span class="input-group-btn">
<button type="button" class="quantity-right-plus btn btn-success btn-number" data-type="plus" data-field="">
<span class="glyphicon glyphicon-plus"></span>
</button>
</span>
</div>
</div>
<div class="col-lg-2">
Good something
<div class="input-group">
<span class="input-group-btn">
<button type="button" class="quantity-left-minus btn btn-danger btn-number" data-type="minus" data-field="">
<span class="glyphicon glyphicon-minus"></span>
</button>
</span>
<input type="text" id="candy4" name="quantity" class="form-control input-number" value="0" min="0" max="20">
<span class="input-group-btn">
<button type="button" class="quantity-right-plus btn btn-success btn-number" data-type="plus" data-field="">
<span class="glyphicon glyphicon-plus"></span>
</button>
</span>
</div>
</div>
<div class="col-lg-2 center-block ">
<div class="input-group center-block">
<button class="btn btn-magick center-block" onClick="submitOrder()">Place sweet order!</button>
</div>
</div>
</div>
</div>
</body>
</html>
Binary file not shown.
Binary file not shown.
+34 -30
View File
@@ -1,59 +1,63 @@
#include "HX711.h" #include <HX711.h>
HX711 scale; HX711 scale;
void setup() { void setup() {
Serial.begin(38400); Serial.begin(115200);
Serial.println("HX711 Demo"); //Serial.println("HX711 Demo");
Serial.println("Initializing the scale"); //Serial.println("Initializing the scale");
// parameter "gain" is ommited; the default value 128 is used by the library // parameter "gain" is ommited; the default value 128 is used by the library
// HX711.DOUT - pin #A1 // HX711.DOUT - pin #A1
// HX711.PD_SCK - pin #A0 // HX711.PD_SCK - pin #A0
scale.begin(2, 3); scale.begin(2, 3);
Serial.println("Before setting up the scale:"); //Serial.println("Before setting up the scale:");
Serial.print("read: \t\t"); //Serial.print("read: \t\t");
Serial.println(scale.read()); // print a raw reading from the ADC //Serial.println(scale.read()); // print a raw reading from the ADC
Serial.print("read average: \t\t"); //Serial.print("read average: \t\t");
Serial.println(scale.read_average(20)); // print the average of 20 readings from the ADC //Serial.println(scale.read_average(20)); // print the average of 20 readings from the ADC
Serial.print("get value: \t\t"); //Serial.print("get value: \t\t");
Serial.println(scale.get_value(5)); // print the average of 5 readings from the ADC minus the tare weight (not set yet) //Serial.println(scale.get_value(5)); // print the average of 5 readings from the ADC minus the tare weight (not set yet)
Serial.print("get units: \t\t"); //Serial.print("get units: \t\t");
Serial.println(scale.get_units(5), 1); // print the average of 5 readings from the ADC minus tare weight (not set) divided //Serial.println(scale.get_units(5), 1); // print the average of 5 readings from the ADC minus tare weight (not set) divided
// by the SCALE parameter (not set yet) // by the SCALE parameter (not set yet)
scale.set_scale(2280.f); // this value is obtained by calibrating the scale with known weights; see the README for details scale.set_scale(2280.f); // this value is obtained by calibrating the scale with known weights; see the README for details
scale.tare(); // reset the scale to 0 scale.tare(); // reset the scale to 0
Serial.println("After setting up the scale:"); //Serial.println("After setting up the scale:");
Serial.print("read: \t\t"); //Serial.print("read: \t\t");
Serial.println(scale.read()); // print a raw reading from the ADC //Serial.println(scale.read()); // print a raw reading from the ADC
Serial.print("read average: \t\t"); //Serial.print("read average: \t\t");
Serial.println(scale.read_average(20)); // print the average of 20 readings from the ADC //Serial.println(scale.read_average(20)); // print the average of 20 readings from the ADC
Serial.print("get value: \t\t"); //Serial.print("get value: \t\t");
Serial.println(scale.get_value(5)); // print the average of 5 readings from the ADC minus the tare weight, set with tare() //Serial.println(scale.get_value(5)); // print the average of 5 readings from the ADC minus the tare weight, set with tare()
Serial.print("get units: \t\t"); //Serial.print("get units: \t\t");
Serial.println(scale.get_units(5), 1); // print the average of 5 readings from the ADC minus tare weight, divided //Serial.println(scale.get_units(5), 1); // print the average of 5 readings from the ADC minus tare weight, divided
// by the SCALE parameter set with set_scale // by the SCALE parameter set with set_scale
Serial.println("Readings:"); //Serial.println("Readings:");
} }
void loop() { void loop() {
Serial.print("one reading:\t"); //Serial.print("one reading:\t");
Serial.print(scale.get_units(), 1); //Serial.print(scale.get_units(), 1);
Serial.print("\t| average:\t"); //Serial.print("\t| average:\t");
Serial.println(scale.get_units(10), 1); if (Serial.available() > 0) {
Serial.read();
Serial.println(scale.get_units(), 1);
scale.power_down(); // put the ADC in sleep mode //scale.power_down(); // put the ADC in sleep mode
delay(500); //delay(100);
scale.power_up(); //scale.power_up();
}
} }
BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 44 KiB

BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 30 KiB

BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 296 KiB

BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 224 KiB

BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 54 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 273 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 281 KiB

+157
View File
@@ -0,0 +1,157 @@
import cv2
import time
import serial
from xmlrpc.server import SimpleXMLRPCServer
from xmlrpc.server import SimpleXMLRPCRequestHandler
from threading import Thread
import numpy as np
cap = cv2.VideoCapture(-1)
font = cv2.FONT_HERSHEY_SIMPLEX
list_img = cv2.imread('list.jpg')
list_img = cv2.resize(list_img,None,fx=0.8, fy=0.8, interpolation = cv2.INTER_CUBIC)
target_w = 50
candy1_img = cv2.imread('candy1.jpg')
factor = target_w / candy1_img.shape[0]
candy1_img = cv2.resize(candy1_img,None,fx=factor, fy=factor, interpolation = cv2.INTER_CUBIC)
candy2_img = cv2.imread('candy2.jpg')
factor = target_w / candy2_img.shape[0]
candy2_img = cv2.resize(candy2_img,None,fx=factor, fy=factor, interpolation = cv2.INTER_CUBIC)
candy3_img = cv2.imread('candy3.jpg')
factor = target_w / candy3_img.shape[0]
candy3_img = cv2.resize(candy3_img,None,fx=factor, fy=factor, interpolation = cv2.INTER_CUBIC)
candy4_img = cv2.imread('candy4.jpg')
factor = target_w / candy4_img.shape[0]
candy4_img = cv2.resize(candy4_img,None,fx=factor, fy=factor, interpolation = cv2.INTER_CUBIC)
img_list = [candy1_img, candy2_img, candy3_img, candy4_img]
IMG_W = 1280
IMG_H = 720
rect_w = 220
rect_h = 52
weights_list = [37.0, 4.8, 8.8, 2.5]
ARDUPORT = 'COM12'
serial = serial.Serial(ARDUPORT, 115200, timeout=1)
candy_stat = []
# s = {}
# s['img_idx'] = 0
# s['loaded'] = 0
# s['required'] = 4
# candy_stat.append(s)
# s = {}
# s['img_idx'] = 1
# s['loaded'] = 0
# s['required'] = 2
# candy_stat.append(s)
# s = {}
# s['img_idx'] = 2
# s['loaded'] = 0
# s['required'] = 6
# candy_stat.append(s)
# s = {}
# s['img_idx'] = 3
# s['loaded'] = 0
# s['required'] = 9
# candy_stat.append(s)
previous_weight = 0
def new_order(params):
global candy_stat
print ('Got order ')
print(params)
candy_stat = params
return True
def async_server_megahack(server):
server.serve_forever()
# Restrict to a particular path.
class RequestHandler(SimpleXMLRPCRequestHandler):
rpc_paths = ('/RPC2',)
def check_endgame(params):
for s in candy_stat:
if s['required'] != s['loaded']:
return False
return True
def is_equal_with_tolerance(v1, v2, t):
return (v2 * (1-t) < v1) and (v2 * (1+t) > v1)
did_change = False
def check_weights(params, new_weight):
global previous_weight, did_change
weight_diff = new_weight - previous_weight
if weight_diff < 0.3:
return
elif not did_change:
did_change = True
else:
for i in range(4):
if is_equal_with_tolerance(weight_diff, weights_list[i], 0.1):
params[i]['loaded'] += 1
previous_weight = new_weight
did_change = False
break
if did_change:
did_change = False
previous_weight = new_weight
def draw_rectangles(img, n):
for i in range(n):
cv2.rectangle(img, (IMG_W - 5 - rect_w,5 + (rect_h + 5)*i), (IMG_W - 5, 5 + (rect_h + 5)*i + rect_h), (255, 255, 255), -1)
def print_stats(img, stats):
# draw_rectangles(img, len(stats))
img[0:list_img.shape[0], IMG_W-list_img.shape[1]:IMG_W, :] = list_img[:]
for i in range(len(stats)):
cv2.putText(img,str(stats[i]['loaded']),(IMG_W - 130,188 + i * (rect_h + 5)), font, 1.3,(0, 0, 0),2,cv2.LINE_AA)
cv2.putText(img,"/",(IMG_W - 90,188 + i * (rect_h + 5)), font, 1.3,(0, 0, 0),2,cv2.LINE_AA)
cv2.putText(img,str(stats[i]['required']),(IMG_W - 50,188 + i * (rect_h + 5)), font, 1.3,(0, 0, 0),2,cv2.LINE_AA)
img[150+(rect_h + 5)*i:150+(rect_h + 5)*i + target_w, IMG_W-130-target_w-20:IMG_W-130-20, :] = img_list[stats[i]['img_idx']][:]
cv2.namedWindow("window", cv2.WND_PROP_FULLSCREEN)
cv2.setWindowProperty("window",cv2.WND_PROP_FULLSCREEN,cv2.WINDOW_FULLSCREEN)
with SimpleXMLRPCServer(('localhost', 8000),
requestHandler=RequestHandler) as server:
server.register_introspection_functions()
server.register_function(new_order)
t = Thread(target=async_server_megahack, args=(server,))
t.start()
# serial.write(b'e')
# line = serial.readline()[:-2]
# print (line)
# weight = -float(line)
# previous_weight = weight
frame_counter = 0
weight = 0
canvas = np.zeros((720, 1280, 3)).astype(np.uint8)
while True:
frame_counter += 1
if frame_counter == 75:
serial.write(b'e')
weight = -float(serial.readline()[:-2])
frame_counter = 0
print(weight)
check_weights(candy_stat, weight)
if check_endgame(candy_stat):
candy_stat = []
# TODO: do funny gif
ret, frame = cap.read()
frame = cv2.resize(frame,None,fx=1.5, fy=1.5, interpolation = cv2.INTER_CUBIC)
canvas[0:720, 0:960, :] = frame[:]
if (len(candy_stat) > 0):
print_stats(canvas, candy_stat)
cv2.imshow("window", canvas)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
# When everything done, release the capture
cap.release()
cv2.destroyAllWindows()