def updateDispensing(self, mixing=True): ml_left = [] dispenselist = self.dispenselist self.ser = SerialConnection() ml_left = self.ser.readLine().split(",") logging.debug(str(ml_left[0])) if not "ok" in ml_left[0]: for ingr in self.dispensing: logging.debug(ingr.feed.name) for pumpnumber in list(range(24)): if ingr.feed.motor_num == pumpnumber: if "Ready" in ml_left[0]: ingr.dispensed = 0 else: logging.debug("pumpnumber ", str(pumpnumber)) if int(ml_left[pumpnumber]) < 0: ml_left[pumpnumber] = 0 ingr.dispensed = math.ceil( (dispenselist[pumpnumber] - int(ml_left[pumpnumber])) / self.stepsforml) else: self.ser.close() del self.ser hwa = HardwareAction(self.mixit) hwa.end_dispensing(self.mixit) self.dispensing[:] = [x for x in self.dispensing if not x.done()]
def __init__(self, master, amount, turns, pumpcount=1): super(CleanScreen, self).__init__(master) self.master = master self.last_disp = 0.0 self.pumpnumber = 0 self.turn = 0 self.amount = amount self.turns = turns self.pumpcount = pumpcount self.stopCleaning = False self.desc = Text(self, relief=FLAT, wrap=NONE, state=DISABLED) backbtn = RectButton(self, text="Abbruch", command=self.handle_button_back) self.bgcolor = master.bgcolor self.configure(bg=self.bgcolor) self.desc.grid(column=0, row=0, sticky=N + E + W + S) backbtn.grid(column=0, row=1, padx=10, pady=10, sticky=E + W + S) self.grid_columnconfigure(0, weight=1) self.grid_rowconfigure(0, weight=1) try: self.ser.readData() except: try: self.ser = SerialConnection() self.ser.readData() except: logging.debug("Verbindung nicht moeglich") self.next_Pump()
def cancelDispensing(self): self.ser = SerialConnection() self.ser.sendData('@') self.ser.readLine() self.ser.close() del self.ser logging.debug("Ausschenken abgebrochen") for ingr in self.dispensing: ingr.stopFeed() self.dispensing[:] = [x for x in self.dispensing if not x.done()]
def startDispensing(self, volume): stepsforml = self.stepsforml tot_vol = self.totalVolume() vol_mult = volume / tot_vol self.dispensing = [] sercommand = '' self.dispenselist = [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ] logging.info("Dispensing: %s, %d ml" % (self.getName(), volume)) for ingr in self.ingredients: ingr.milliliters = math.ceil(ingr.milliliters * vol_mult) self.dispensing.append(DispensingIngredient(ingr, vol_mult)) for ingr in self.dispensing: thisfeed = SupplyFeed.getByName(ingr.feed.name) newremaining = thisfeed.feeds[ ingr.feed.name].remaining - ingr.milliliters thisfeed.feeds[ingr.feed.name].remaining = newremaining logging.debug("remaining neu fuer " + ingr.feed.name + ": " + str(thisfeed.feeds[ingr.feed.name].remaining)) logging.info("Zutat " + ingr.feed.name + ": " + str(ingr.milliliters) + " ml") for pumpnumber in list(range(24)): if ingr.feed.motor_num == pumpnumber: self.dispenselist[pumpnumber] = int( math.ceil(ingr.milliliters * self.stepsforml)) sercommand = (','.join(map(str, self.dispenselist))) + '\n' try: self.ser.readData() except: logging.debug("keine bestehende verbindung") try: self.ser = SerialConnection() self.ser.readData() logging.debug("habe verbindung") except: logging.debug("verbindung nicht moeglich") hwa = HardwareAction(self.mixit) hwa.do_dispensing(self.mixit) self.ser.sendData(sercommand) self.ser.close() del self.ser self.updateDispensing(self.mixit)
def __init__(self): # Create an INET, STREAMing socket self.cli_sock = socket.socket( socket.AF_INET, socket.SOCK_STREAM) # Connect to a remote socket at host and port self.cli_sock.connect(('pi2' , 1234)) self.serial_conn = SerialConnection('/dev/ttyUSB0', 30) self.serial_conn.open() self.serial_conn.flush_input()
def __init__(self, master, recipe, amount): super(DispensingScreen, self).__init__(master) self.master = master self.ser = SerialConnection() self.recipe = recipe self.last_disp = 0.0 self.desc = Text(self, relief=FLAT, wrap=NONE, state=DISABLED) backbtn = RectButton(self, text="Abbruch", command=self.handle_button_back) self.bgcolor = master.bgcolor self.configure(bg=self.bgcolor) self.desc.grid(column=0, row=0, sticky=N+E+W+S) backbtn.grid(column=0, row=1, padx=10, pady=10, sticky=E+W+S) self.grid_columnconfigure(0, weight=1) self.grid_rowconfigure(0, weight=1) recipe.startDispensing(amount) self.pid = self.after(UPDATE_MS, self.update_screen)
class NetworkClient: """A class for sending readings to a server""" def __init__(self): # Create an INET, STREAMing socket self.cli_sock = socket.socket( socket.AF_INET, socket.SOCK_STREAM) # Connect to a remote socket at host and port self.cli_sock.connect(('pi2' , 1234)) self.serial_conn = SerialConnection('/dev/ttyUSB0', 30) self.serial_conn.open() self.serial_conn.flush_input() def send(self): try: while True: data = self.serial_conn.read() self.cli_sock.send(data) except KeyboardInterrupt: self.serial_conn.close() self.cli_sock.close()
class Main: """A class for establishing connections""" def start_db_hdlr(self, db): self.db_hdlr = DatabaseHandler(db) self.db_hdlr.flush_rss_readings() self.db_hdlr.check_pos_tbl() self.db_hdlr.check_rsl_tbl() def start_net_srv(self): self.net_srv = NetworkServer() self.net_srv.start() def start_serial_conn(self, port, timeout): self.serial_conn = SerialConnection(port, timeout) self.serial_conn.open() self.serial_conn.flush_input() def start_trilat(self): self.trilat = Trilateration() self.trilat.start() def run(self): try: while True: data = self.serial_conn.read().strip() tag_id = data[:4] rss = data[4:] self.db_hdlr.ins_reading(2, tag_id, rss) except KeyboardInterrupt: self.db_hdlr.close_db() self.net_srv.stop() self.net_srv.join(60) self.trilat.stop() self.trilat.join(20) self.serial_conn.close()
nav_status_lock = threading.Lock() command = 6 * [0] command_lock = threading.Lock() # global variables mission_running = True mission_mode = True blocking = True thread1 = None thread2 = None obj_detection = ObjectDetection() # initializing serial connection with AUV_simulator simulator_com = SerialConnection(port='com1', baud=115200) simulator_com.start() # wait for the first not empty message from AUV_simulator while nav_status == None: receive_nav_status() # threads running start_threads() # wait for threads termination wait_for_threads_termination() # close serial connection with AUV_simulator simulator_com.close()
class Recipe(object): recipes = {} recipe_types = {} by_feed = {} def __init__(self, type_, name, ingredients, mixit, icon): global type_icons if type_ not in type_icons: raise UnknownRecipeTypeError() if type_ not in Recipe.recipe_types: Recipe.recipe_types[type_] = [] Recipe.recipe_types[type_].append(self) self.type_ = type_ self.name = name self.icon = icon self.mixit = mixit self.ingredients = [] self.dispensing = [] self.timeslice_secs = 1.0 self.min_dispense_secs = 0.1 self.last_timeslice = time.time() self.last_update_time = time.time() self.stepsforml = 136 # number of steps for 1 ml Recipe.recipes[name] = self for ingr_data in ingredients: ingr = Ingredient.fromArray(ingr_data) if ingr.feed not in Recipe.by_feed: Recipe.by_feed[ingr.feed] = [] Recipe.by_feed[ingr.feed].append(self) self.ingredients.append(ingr) @classmethod def fromDict(cls, d): """Create new Recipe instances from a dictionary description.""" global type_icons if 'type_icons' in type_icons: type_icons = d['type_icons'] # Delete old Recipes for name, recipe in cls.recipes.items(): recipe.delete_recipe() # Add Recipes from dict for name, data in d.get('recipes', {}).items(): cls( data['type'], name, data['ingredients'], data['mixit'], icon=data.get('icon'), ) @classmethod def toDictAll(cls, d, metric=True): """Create a dictionary description of all Recipe instances.""" global type_icons d['recipes'] = { name: recipe.toDict(metric=metric) for name, recipe in cls.recipes.items() } d['type_icons'] = type_icons return d def toDict(self, metric=True): data = { 'type': self.type_, 'ingredients': [x.toArray(metric=metric) for x in self.ingredients], 'mixit': self.mixit, } if self.icon: data['icon'] = self.icon return data @classmethod def getTypeNames(cls): return sorted(cls.recipe_types.keys()) @staticmethod def getPossibleTypeNames(): global type_icons return sorted(type_icons.keys()) @classmethod def getTypeIcon(cls, name): global type_icons return type_icons[name] @classmethod def getRecipesByType(cls, name): recipe_list = cls.recipe_types[name] return sorted(recipe_list, key=operator.attrgetter('name')) @classmethod def getRecipesKeysByType(cls, name): recipe_list = cls.recipe_types[name] for key in sorted(cls.recipes.keys()): if cls.getByName(name=key) in recipe_list: yield cls.recipes[key] @classmethod def getRecipesByFeed(cls, feed): if feed not in cls.by_feed: return [] recipe_list = cls.by_feed[feed] return sorted(recipe_list, key=operator.attrgetter('name')) @classmethod def getNames(cls): return sorted(cls.recipes.keys()) @classmethod def getAll(cls): for key in sorted(cls.recipes.keys()): yield cls.recipes[key] @classmethod def getByName(cls, name): return cls.recipes[name] def getName(self): return self.name def getType(self): return self.type_ def getMixit(self): return self.mixit def getIcon(self): return self.icon def delete_recipe(self): del Recipe.recipes[self.name] Recipe.recipe_types[self.type_].remove(self) if not Recipe.recipe_types[self.type_]: del Recipe.recipe_types[self.type_] for ingr in self.ingredients: Recipe.by_feed[ingr.feed].remove(self) if not Recipe.by_feed[ingr.feed]: del Recipe.by_feed[ingr.feed] def rename(self, newname): del Recipe.recipes[self.name] self.name = newname Recipe.recipes[newname] = self def retype(self, newtype): global type_icons if newtype not in type_icons: raise UnknownRecipeTypeError() if newtype not in Recipe.recipe_types: Recipe.recipe_types[newtype] = [] Recipe.recipe_types[self.type_].remove(self) if not Recipe.recipe_types[self.type_]: del Recipe.recipe_types[self.type_] self.type_ = newtype Recipe.recipe_types[newtype].append(self) def add_ingredient(self, feedname, ml): feed = SupplyFeed.getByName(feedname) if feed not in Recipe.by_feed: Recipe.by_feed[feed] = [] Recipe.by_feed[feed].append(self) self.ingredients.append(Ingredient(feed, ml)) return self def canMake(self): for ingr in self.ingredients: if not ingr.feed.avail or ingr.feed.remaining <= 0: return False return True def getAlcoholPercentByVolume(self): vol = 0.0 alc_vol = 0.0 for ingr in self.ingredients: ml = ingr.milliliters vol += ml alc_vol += ml * (ingr.feed.proof / 100.0) return 100.0 * alc_vol / vol def totalVolume(self): vol = 0.0 for ingr in self.ingredients: vol += ingr.milliliters return vol def startDispensing(self, volume): stepsforml = self.stepsforml tot_vol = self.totalVolume() vol_mult = volume / tot_vol self.dispensing = [] sercommand = '' self.dispenselist = [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ] logging.info("Dispensing: %s, %d ml" % (self.getName(), volume)) for ingr in self.ingredients: ingr.milliliters = math.ceil(ingr.milliliters * vol_mult) self.dispensing.append(DispensingIngredient(ingr, vol_mult)) for ingr in self.dispensing: thisfeed = SupplyFeed.getByName(ingr.feed.name) newremaining = thisfeed.feeds[ ingr.feed.name].remaining - ingr.milliliters thisfeed.feeds[ingr.feed.name].remaining = newremaining logging.debug("remaining neu fuer " + ingr.feed.name + ": " + str(thisfeed.feeds[ingr.feed.name].remaining)) logging.info("Zutat " + ingr.feed.name + ": " + str(ingr.milliliters) + " ml") for pumpnumber in list(range(24)): if ingr.feed.motor_num == pumpnumber: self.dispenselist[pumpnumber] = int( math.ceil(ingr.milliliters * self.stepsforml)) sercommand = (','.join(map(str, self.dispenselist))) + '\n' try: self.ser.readData() except: logging.debug("keine bestehende verbindung") try: self.ser = SerialConnection() self.ser.readData() logging.debug("habe verbindung") except: logging.debug("verbindung nicht moeglich") hwa = HardwareAction(self.mixit) hwa.do_dispensing(self.mixit) self.ser.sendData(sercommand) self.ser.close() del self.ser self.updateDispensing(self.mixit) def updateDispensing(self, mixing=True): ml_left = [] dispenselist = self.dispenselist self.ser = SerialConnection() ml_left = self.ser.readLine().split(",") logging.debug(str(ml_left[0])) if not "ok" in ml_left[0]: for ingr in self.dispensing: logging.debug(ingr.feed.name) for pumpnumber in list(range(24)): if ingr.feed.motor_num == pumpnumber: if "Ready" in ml_left[0]: ingr.dispensed = 0 else: logging.debug("pumpnumber ", str(pumpnumber)) if int(ml_left[pumpnumber]) < 0: ml_left[pumpnumber] = 0 ingr.dispensed = math.ceil( (dispenselist[pumpnumber] - int(ml_left[pumpnumber])) / self.stepsforml) else: self.ser.close() del self.ser hwa = HardwareAction(self.mixit) hwa.end_dispensing(self.mixit) self.dispensing[:] = [x for x in self.dispensing if not x.done()] def cancelDispensing(self): self.ser = SerialConnection() self.ser.sendData('@') self.ser.readLine() self.ser.close() del self.ser logging.debug("Ausschenken abgebrochen") for ingr in self.dispensing: ingr.stopFeed() self.dispensing[:] = [x for x in self.dispensing if not x.done()] def doneDispensing(self): return not self.dispensing
control_mode = False mission_mode = False #--------------------------------------------------------------------------------# # inizializing UDP connection with Unity HOST_IP = 'localhost' HOST_PORT_UDP = 29000 UDP_IP = 'localhost' UDP_PORT = 25000 unity_com = CustomUDP(HOST_IP, HOST_PORT_UDP, UDP_IP, UDP_PORT) unity_com.start() # inizializing connection with mission_manager mission_com = SerialConnection(port='com2', baud=115200) mission_com.start() # inizializing pygame pg.init() # creation GUI screen pg.display.set_caption('Zeno GUI') screen = pg.display.set_mode(SCREEN_DIM) # creation of stylised images of the AUV (top, side and back view) # note: images are square and image width is equal to dial diameter image_width = 2 * DIAL_R image_1 = create_view('images/zeno_top.bmp', image_width) # top view image_2 = create_view('images/zeno_side.bmp', image_width) # side view
from serial_connection import SerialConnection import signal def new_packet(incoming_queue): packet = incoming_queue.get() print(packet) incoming_queue.task_done() def exit_handler(signal, frame): print("Exit called") con.stop() con = SerialConnection('/dev/pts/2', 19200, new_packet, "ACK\n") items = ["esimene", "teine", "kolmas", "neljas"] con.start() for i in items: con.write(i) print("items added to write queue") # register exit handler signal.signal(signal.SIGINT, exit_handler)
def start_serial_conn(self, port, timeout): self.serial_conn = SerialConnection(port, timeout) self.serial_conn.open() self.serial_conn.flush_input()
class CleanScreen(Frame): def __init__(self, master, amount, turns, pumpcount=1): super(CleanScreen, self).__init__(master) self.master = master self.last_disp = 0.0 self.pumpnumber = 0 self.turn = 0 self.amount = amount self.turns = turns self.pumpcount = pumpcount self.stopCleaning = False self.desc = Text(self, relief=FLAT, wrap=NONE, state=DISABLED) backbtn = RectButton(self, text="Abbruch", command=self.handle_button_back) self.bgcolor = master.bgcolor self.configure(bg=self.bgcolor) self.desc.grid(column=0, row=0, sticky=N + E + W + S) backbtn.grid(column=0, row=1, padx=10, pady=10, sticky=E + W + S) self.grid_columnconfigure(0, weight=1) self.grid_rowconfigure(0, weight=1) try: self.ser.readData() except: try: self.ser = SerialConnection() self.ser.readData() except: logging.debug("Verbindung nicht moeglich") self.next_Pump() def next_Pump(self): sercommand = '' self.pid = None self.dispenselist = [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ] for currentpump in range(self.pumpnumber, (self.pumpnumber + self.pumpcount)): if currentpump < 24: self.dispenselist[currentpump] = 136 * self.amount sercommand = (','.join(map(str, self.dispenselist))) + '\n' print(sercommand) self.pumpnumber += self.pumpcount - 1 self.ser.sendData(sercommand) if self.pumpnumber >= 23: self.pumpnumber = 0 self.turn += 1 else: self.pumpnumber += +1 if self.turn >= self.turns: self.stopCleaning = True self.master.screen_pop_to_top() self.pid = self.after(UPDATE_MS, self.update_screen) def update_screen(self): self.pid = None if not self.stopCleaning: serout = '' serout = str(self.ser.readLine()) if bool(re.search(r'ok', serout)): logging.debug("ok gefunden") self.next_Pump() else: try: bool(re.search(r'\d+,\d+', serout)) ml_left = serout.split(",") logging.debug("pumpnumber " + str(self.pumpnumber)) self.desc.config(state=NORMAL) self.desc.delete(0.0, END) self.desc.tag_config("header", background="#077", foreground="white") self.desc.tag_config("pumpnumber", lmargin1=10, lmargin2=20) self.desc.tag_config("left", foreground="#c44") self.desc.insert(END, "Cleaning Pump: ", "header") self.desc.insert( END, str( list( range((self.pumpnumber - self.pumpcount), self.pumpnumber))), "pumpnumber") self.desc.insert( END, " left %.0f ml\n" % math.ceil( int(ml_left[self.pumpnumber - self.pumpcount]) / 136), 'left') self.desc.config(state=DISABLED) except ValueError: print("That's not an int!") self.master.update() self.pid = self.after(UPDATE_MS, self.update_screen) def handle_button_back(self): if self.pid != None: self.after_cancel(self.pid) self.turn = 5 self.stopCleaning = True self.master.screen_pop() def hasNumbers(inputString): return any(char.isdigit() for char in inputString)