コード例 #1
0
    def __init__(self, verbose, bluetooth, fakeData, setupTags, websocket,
                 recipeHandler):
        super().__init__()

        self.websocket = websocket
        self.recipeHandler = recipeHandler

        # initialize threads
        self.orderHandler = OrderHandler(self.recipeHandler, verbose, fakeData,
                                         websocket)
        self.orderHandler.start()
        self.keyboardHandler = KeyboardHandler()
        self.keyboardHandler.start()
        self.serialHandler = SerialHandler()
        self.serialHandler.start()

        # nothing to send yet
        self.message = ""
        self.afterStartup = True
        self.ignoreInputs = False

        self.setupTags = setupTags
        self.bluetoothHandler = False
        if bluetooth:
            self.bluetoothHandler = BluetoothHandler()
        else:
            print("No Bluetooth available")
コード例 #2
0
def getSerialPort():
    serial_port_list = serial_ports()
    valid_serial_port = None
    for serial_port in serial_port_list:
        # Connect to serial port
        serial_device = SerialHandler()
        serial_device.start(serial_port, BAUD_RATE, timeout_seconds=1)

        # Stop recording if MCU is recording
        serial_device.send_string('0')
        time.sleep(READ_DELAY_SECONDS)

        # Send call to verify connection
        serial_device.send_string('J')
        time.sleep(READ_DELAY_SECONDS)
        response = serial_device.pop_bytes_all()

        # Check if response is valid
        if response == b'I':
            valid_serial_port = serial_port

        # Close connection
        del serial_device

        # If a valid port was found, break
        if valid_serial_port:
            break

    return valid_serial_port
コード例 #3
0
ファイル: scanner.py プロジェクト: wumzi/mines_S3DHQ
	def __init__(self, folder="data", device="/dev/ttyACM0", baudrate="115200"):
		if not os.path.exists(folder):
			os.mkdir(folder)
		os.chdir(folder)

		self.camera = CameraHandler(model="canonEOS")
		self.serial = SerialHandler(device, baudrate)

		self.pause = False
		self.last_position = (0, 0)

		self.panneau1 = self.panneau2 = self.panneau3 = (0, 0, 0)
コード例 #4
0
        'measured': [0.1, 0.2, -0.1, -0.2],
        'input_pressure': 30
    },
    {
        '_command': 'SET',
        '_args': "0,4,6"
    },
    {
        'time': 5,
        'setpoints': [0, 0, 0, 0],
        'measured': [0.1, 0.2, -0.1, -0.2],
        'input_pressure': 30
    },
]
csv_file = "Names.csv"

# Import a few utility modules
import sys
sys.path.insert(0, 'utils')
from serial_handler import SerialHandler

if __name__ == "__main__":
    ser = SerialHandler()
    ser.read_serial_settings()
    ser.initialize()
    ser.save_init('TESTING.csv')

    for line in dict_data:
        ser.save_data_line(line)

    ser.shutdown()
コード例 #5
0
ファイル: hub.py プロジェクト: yarsanich/rest-radio
shared_manager = Manager()
# make a shared variable, based on our preset hub_variables
# NOTE: when updating an inside dict, use the top level dictionary.
shared_dict = shared_manager.dict(hub_variables)

auto_detect = False
# if auto-detect is False, this path will be used.
selected = "/dev/cu.usbmodem1462"

if auto_detect:
    selected = auto_detect_microbit()

    if selected is None:
        raise Exception("No Bridge Detected")

serial_handler = SerialHandler(selected)

# load translations JSON file
translationsFile = open("./translations.json")
translations = json.load(translationsFile)
github_poller = URLPoller(hub_variables["translations_json"]["url"],
                          hub_variables["translations_json"]["poll_time"])

packet_count = 0

try:
    while (True):

        # if the bridged micro:bit has sent us data, process
        if serial_handler.buffered() > 0:
            rPacket = RadioPacket(serial_handler.read_packet())
コード例 #6
0
#All rights reserved.
#THIS SOFTWARE IS PROVIDED "AS IS".
#IN NO EVENT WILL THE COPYRIGHT OWNER BE LIABLE FOR ANY DAMAGES
#ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE.

import rospy
from std_msgs.msg import String
from sensor_msgs.msg import Image
import cv2
import cv_bridge
from cv_bridge import CvBridgeError
from gpsClass import gps_data
from serial_handler import SerialHandler
import math
PARSER = gps_data()
SERIAL_HANDLER = SerialHandler('/dev/ttyUSB0', 9600)
count = 0

def image_callback(data):
    global PARSER
    global SERIAL_HANDLER
    global count
    rospy.loginfo("Received image") #use this for debugging
    try:
        cv_image= cv_bridge.CvBridge().imgmsg_to_cv2(data, "bgr8")
        #cv2.imshow('my_image_feed', cv_image)
        PARSER.image = cv_image
        (x,y) = PARSER.get_x_y()
        if math.isnan(x):
            return
        count = count + 1
コード例 #7
0
ファイル: protocol_parser.py プロジェクト: ericho/moxa_api
class ProtocolParser(object):
    """ A RS232 to ZigBee protocol parser """

    def __init__(self, port):
        self.sh = SerialHandler()
        self.sh.open_device(port)

    def terminate(self):
        self.sh.close_device()

    def send_command(self, cmd):
        stream = self.command_to_frame(cmd)
        self.sh.write(stream)

    def receive_command(self):
        """ Reads from serial port until the FOOTER has arrived, then parses
            all the data and converts into a FrameCommand instance.
            This instance is returned.
        """
        recv = self.sh.read_data()
        if self._is_valid_frame(recv):
            return self.frame_to_object(recv)
        else:
            return None

    def frame_to_object(self, data):
        """ Extracts the data from a data frame and create an object
            of FrameCommand
        """
        if len(data) < 6:
            return None

        cmd = FrameCommand()
        cmd.id_message = struct.unpack('B', data[3])[0]
        cmd.command = struct.unpack('B', data[4])[0]
        cmd.data_length = struct.unpack('!H', data[1] + data[2])[0]
        if cmd.data_length > 0:
            cmd.data = data[5:len(data)-1]
        else:
            cmd.data = None

        return cmd

    def command_to_frame(self, cmd):
        """ Converts a FrameCommand instance into a serial data frame
            to be send through serial port
        """
        packed_data = HEADER
        packed_data += '\x00'
        packed_data += struct.pack('B', cmd.data_length + 6)
        packed_data += struct.pack('B', cmd.id_message)
        packed_data += struct.pack('B', cmd.command)
        if cmd.data_length > 0:
            for i in cmd.data:
                packed_data += cmd.data[i]
        packed_data += FOOTER
        return packed_data

    def _is_valid_frame(self, data):
        """ Checks if data meets the basic struture to be considered
            a data frame in the protocol
        """
        if len(data) < 6:
            return False

        if data[0] == HEADER and data[len(data) - 1] == FOOTER:
            return True
        return False
コード例 #8
0
ファイル: protocol_parser.py プロジェクト: ericho/moxa_api
 def __init__(self, port):
     self.sh = SerialHandler()
     self.sh.open_device(port)
コード例 #9
0
ファイル: scanner.py プロジェクト: wumzi/mines_S3DHQ
class ScannerHandler():

	X_POS = 60
	Z_POS = 30
	already_photographed = None
	last_position = (None, None)
	pause = False

	def __init__(self, folder="data", device="/dev/ttyACM0", baudrate="115200"):
		if not os.path.exists(folder):
			os.mkdir(folder)
		os.chdir(folder)

		self.camera = CameraHandler(model="canonEOS")
		self.serial = SerialHandler(device, baudrate)

		self.pause = False
		self.last_position = (0, 0)

		self.panneau1 = self.panneau2 = self.panneau3 = (0, 0, 0)


	def take_picture(self, filename, laser=False):
		self.serial.laser(laser)

		self.camera.take_picture(filename.format(laser))


	def run_scan(self, filenametpl=FILENAMETPL):
		self.already_photographed = list(set([tuple([int(x) for x in filename.split('_')[:2]]) for filename in os.listdir()]))
		
		for z in [z for z in range(91) if not z % self.Z_POS]:
			for x in [x for x in range(360) if not x % self.X_POS]:
				while self.pause:
					time.sleep(1)

				if (z, x) in self.already_photographed:
					continue

				real_z, x = self.reach_position(z, x)
				self.last_position = (real_z, x)

				filename = filenametpl.format(z, x, real_z, "{}")
				self.take_picture(filename, laser=False)
				time.sleep(1)
				self.take_picture(filename, laser=True)
				self.serial.laser(False)

				self.already_photographed.append((z, x))
				


	def reach_position(self, z, x):
		real_z = self.serial.commandeMoteurs(z, x)

		return real_z, x


	def set_lights(self, panneau1=(0, 0, 0), panneau2=(0, 0, 0), panneau3=(0, 0, 0)):
		if self.panneau1 != panneau1:
			self.serial.panneau(0, *panneau1)
		if self.panneau2 != panneau2:
			self.serial.panneau(1, *panneau2)
		if self.panneau3 != panneau3:
			self.serial.panneau(2, *panneau3)
		self.panneau1, self.panneau2, self.panneau3 = panneau1, panneau2, panneau3
		return self.serial.mesureLumiere()


	def get_last_position(self):
		return self.last_position

	def set_pause(self, pause):
		self.pause = pause

	def get_pause(self):
		return self.pause

	def getProgression(self):
		xsteps = 360 / self.X_POS
		zsteps = 91 / self.Z_POS
		return float(len(self.already_photographed)) / (xsteps * zsteps)
コード例 #10
0
import config
from serial_handler import SerialHandler
from window import Window
from graph import Graph
import tkinter as tk

# TODO: setup root with toolbars/buttons

# TODO: setup window with graphs

config = config.get_config()
data = []

window = Window(config)  # Tk window object
window.prompt_serial()

serial = SerialHandler(data, config)
serial.connect()
graph = Graph(data, window)

while True:
    serial.update()
    window.update_idletasks()
    window.update()
    graph.update()

# TODO: register exit handler
save_config(config)
# TODO: save
コード例 #11
0
class InputHandler(threading.Thread):
    def __init__(self, verbose, bluetooth, fakeData, setupTags, websocket,
                 recipeHandler):
        super().__init__()

        self.websocket = websocket
        self.recipeHandler = recipeHandler

        # initialize threads
        self.orderHandler = OrderHandler(self.recipeHandler, verbose, fakeData,
                                         websocket)
        self.orderHandler.start()
        self.keyboardHandler = KeyboardHandler()
        self.keyboardHandler.start()
        self.serialHandler = SerialHandler()
        self.serialHandler.start()

        # nothing to send yet
        self.message = ""
        self.afterStartup = True
        self.ignoreInputs = False

        self.setupTags = setupTags
        self.bluetoothHandler = False
        if bluetooth:
            self.bluetoothHandler = BluetoothHandler()
        else:
            print("No Bluetooth available")

    def setupBluetooth(self):

        # Walk through all our ingredients
        # and wait until there is a tag being moved.
        # This tag will be assigned to the ingredient.
        self.bluetoothHandler.beginSetup()
        for i in self.recipeHandler.ingredients():
            print("setup", i)
            self.message = {
                "setup": 1,
                "recipe": "",
                "waiting": 0,
                "ingredients": {
                    i: "use"
                }
            }
            self.message["action"] = Action.BT_SETUP

            self.sendMessageWithMsg(message=self.message)
            waitForTag = True
            while waitForTag:
                if self.bluetoothHandler.receivedNewInput():
                    mac_address = self.bluetoothHandler.selection()
                    self.bluetoothHandler.setupTag(i, mac_address)
                    waitForTag = False

                time.sleep(.1)

        # Setup ready
        self.bluetoothHandler.setupReady()
        self.message = {"recipe": "", "waiting": 0, "ingredients": {}}
        self.message["action"] = Action.BT_READY

        self.sendMessageWithMsg(message=self.message)

    def run(self):

        #needed for async events (like sending via websocket) that don't need to be awaited
        asyncio.set_event_loop(asyncio.new_event_loop())

        if self.bluetoothHandler and self.setupTags:
            self.setupBluetooth()

        # check user inputs and evaluate which action to take
        # will run infinetly and wait for inputs

        while True:

            # for some reason keyboardInterrupts always reach bluetooththread first
            if self.bluetoothHandler and self.bluetoothHandler.btThread.isAlive(
            ) == False:
                print("bluetooththread quit, exiting")
                os._exit(1)

            if not self.recipeHandler.currentRecipe():
                self.nextRecipe()

            if self.bluetoothHandler and self.bluetoothHandler.receivedNewInput(
            ):
                self.handleBluetoothInput()

            if self.keyboardHandler.receivedNewInput():
                self.handleKeyboardInput()

            if self.serialHandler.receivedNewInput():
                self.handleSerialInput()

            time.sleep(.1)

    def nextRecipe(self):
        self.ignoreInputs = False
        if (self.orderHandler.getQueueLength() != 0 or self.afterStartup):
            print("next recipe")
            self.afterStartup = False
            self.recipeHandler.selectRecipe(self.orderHandler.nextDish())
            self.printStatus()
            self.sendMessage(Action.NEXT_ORDER)
        elif (self.recipeHandler.currentRecipe()):
            print("resetting recipe")
            self.recipeHandler.selectRecipe("")
            self.printStatus()
            self.sendMessage(Action.NEXT_ORDER)

    def nextIngredients(self):
        self.recipeHandler.getNextIngredients()
        self.printStatus()
        if (self.recipeHandler.isReady()):
            self.ignoreInputs = True
            self.sendMessage(Action.NEXT_ORDER)
            time.sleep(5)  #blinking animation
            return

        self.sendMessage(Action.NEXT_INGREDIENT)

    def handleOrderInput(self):
        self.assembleMessage(Action.NEXT_ORDER)

    def handleSerialInput(self, test=None):

        event = []
        if (test == None):
            self.serialHandler.resetInputFlag()
            event = self.serialHandler.getButtonEvent()
            print("Received button event: " + str(event))

        else:
            print("Received button event: " + test)
            event.append(test)
            event.append("D")

        if (event[0] == "0" and event[1] == "D"):
            self.nextIngredients()
        if (event[0] == "1" and event[1] == "D"):
            self.orderHandler.recipeReady()
            self.nextRecipe()
        if (event[0] == "2" and event[1] == "D"):
            self.orderHandler.recipeReady()
            self.orderHandler.reset()
            self.recipeHandler.reset()
            self.nextIngredients()  #TODO remove this hack
        if (event[0] == "3" and event[1] == "D"):
            pass
        if (event[0] == "4" and event[1] == "D"):
            pass
        if (event[0] == "5" and event[1] == "D"):
            self.reboot()
            pass

    def handleKeyboardInput(self):
        userInput = self.keyboardHandler.getInput()

        if userInput == "":
            return

        if userInput in self.recipeHandler.ingredients():
            # entered a valid ingredient

            if (self.ignoreInputs):
                print("ignoring")
                return

            print("- ", userInput)
            self.recipeHandler.useIngredient(userInput)
            if self.recipeHandler.isReady():
                self.ignoreInputs = True
                self.sendMessage(Action.NEXT_INGREDIENT)
                time.sleep(5)
                return
            self.sendMessage(Action.NEXT_INGREDIENT)

        elif userInput in self.recipeHandler.dishes():
            # entered a valid dish
            self.orderHandler.addMealPreparation(userInput, 1)

            #self.sendMessage(Action.NEW_ORDER)

        elif userInput[0] == '#':
            # mock button press
            self.handleSerialInput(userInput[1])

        elif userInput == "status":
            self.printStatus()

        elif userInput == "setup":
            if self.bluetoothHandler:
                self.setupBluetooth()
            else:
                print("No bluetooth to set up")

        elif userInput == "reset":
            # go back to zero
            print("Resetting program...")
            self.recipeHandler.reset()
            self.orderHandler.reset()
            self.sendMessage(Action.CLEAR_QUEUE)

        elif userInput == "exit":
            os._exit(1)

        else:
            print("Unbekannte Eingabe: " + userInput)

    def handleBluetoothInput(self):

        #need to get selected even if we ignore it to reset flag
        selected = self.bluetoothHandler.selection()

        if (self.ignoreInputs):
            return

        if selected in self.recipeHandler.ingredients():
            # entered a valid ingredient
            print("- ", selected)
            self.recipeHandler.useIngredient(selected)
            if self.recipeHandler.isReady():
                self.ignoreInputs = True
                self.sendMessage(Action.NEXT_INGREDIENT)
                time.sleep(5)
                return

            #self.assembleMessage(Action.NEXT_INGREDIENT)

        else:
            # everything else
            print("Unbekannte Eingabe: " + selected)

        print("")
        # wait for 100ms to save resources
        time.sleep(.1)
        self.sendMessage(Action.NEXT_INGREDIENT)

    def printStatus(self):
        print("\n> Current Recipe: ", self.recipeHandler.currentRecipe(),
              self.recipeHandler.currentIngredients(), "///",
              self.orderHandler.getQueueLength(), "in waiting list\n")

    def assembleMessage(self, action):
        # assemble the message to be sent to the web browser
        # it takes the form of a JSON object looking something like this:
        # {
        #	recipe: "Antipasti"
        #	waiting: 4
        #	ingredients: {
        #		banana: "neutral",
        #		tomato: "success",
        #		basil: "error",
        #		...
        #	}
        # }

        if action != Action.CLEAR_QUEUE:
            self.message = {
                "recipe": self.recipeHandler.currentRecipe(),
                "extras": self.recipeHandler.currentExtras(),
                "preparation": self.recipeHandler.currentPreparation(),
                "waiting": self.orderHandler.getQueueLength(),
                "ingredients": {},
                "action": action.value
            }

            # if the recipe is finished, blink for a bit and reset
            if self.recipeHandler.isReady():
                self.message["recipe"] = ""
                self.message["extras"] = ""
                self.message["preparation"] = ""
                for i in self.recipeHandler.ingredients():
                    self.message["ingredients"][i] = "ready"  #blinking
                self.recipeHandler.selectRecipe("")
                self.orderHandler.orderSQLInterface.recipeReady()
                if self.bluetoothHandler:
                    self.bluetoothHandler.resetSelection()

                #time.sleep(5)
            else:
                self.message[
                    "ingredients"] = self.recipeHandler.getIngredientStatus()
                self.message["error"] = self.recipeHandler.getError()

        else:
            self.message = {"action": action}

        # modifying the message so that javascript in the browser can understand it:
        return str(self.message).replace("'", '"')

    def sendMessage(self, action):
        loop = asyncio.get_event_loop()
        task = loop.create_task(
            self.websocket.sendMessage(self.assembleMessage(action)))
        loop.run_until_complete(task)

    def sendMessageWithMsg(self, message):
        loop = asyncio.get_event_loop()
        task = loop.create_task(self.websocket.sendMessage(message))
        loop.run_until_complete(task)

    def reboot(self):
        print("restarting")
        time.sleep(1)
        asyncio.set_event_loop(asyncio.new_event_loop())
        # notify the frontends to restart in 10 s and then so long until the server is back again
        self.sendMessage(Action.RESTART)
        os.system('reboot')
        #os.execv(sys.executable, ['python'] + sys.argv)
コード例 #12
0
auto_detect = False
# if auto-detect is False, this path will be used.
selected = "/dev/ttyACM0"

if auto_detect:
    selected = auto_detect_microbit()

    if selected is None:
        raise Exception("No Bridge Detected")

#cloud_variable_ep = CloudVariableEp(hub_variables)

#this class can be used to poll an endpoint, I didn't find a real use for it.
# ep_poller = EndpointPoller(translations, hub_variables)

serial_handler = SerialHandler(selected)

# while true swap between polling EPs and receiving / sending.
while (True):

    # if the bridged micro:bit has sent us data, process
    if serial_handler.buffered() > 0:
        rPacket = RadioPacket(serial_handler.read_packet())
        translationsFile = open("./translations.json")
        translations = json.load(translationsFile)
        requestHandler = RequestHandler(rPacket, translations, hub_variables,
                                        None)
        bytes = requestHandler.handleRequest()
        serial_handler.write_packet(bytes)
#   else:
# otherwise check if our asynchronous socket io ep has packets to transmit.
コード例 #13
0
def main():
    blocking_readkey = True
    if sys.platform in ('win32', 'cygwin'):
        blocking_readkey = False
    print("Press R to start recording or Q to quit...")
    while True:
        is_recording = False
        # Wait for R to be pressed
        key = readkey.readkey(blocking=blocking_readkey)
        if key == 'r':
            print("Initialising Recording...")
            is_recording = True
        if key == 'q':
            break
        if is_recording:
            valid = False
            device = None
            try:
                port = getSerialPort()
            except Exception as e:
                print("FATAL ERROR {0}".format(e))
                sys.exit(-1)
            valid = True
            timestamp = datetime.datetime.now().strftime("%Y-%m-%d %H-%M-%S")
            if port is not None:
                try:
                    print("Connecting to device on {0} at baud: {1}".format(
                        port, BAUD_RATE))
                    device = SerialHandler()
                    device.start(
                        port,
                        BAUD_RATE,
                        timeout_seconds=1,
                        log_filename="log/{0} SENSOR DATA".format(timestamp),
                        log_extension="csv",
                        log_show_timestamp=True)
                except SerialException as e:
                    print("CONNECTION ERROR {0}".format(e))
                    port = None
                    valid = False
                    if device:
                        del device
                    device = None
            else:
                valid = False
            if valid:
                if device:
                    try:
                        device.send_string("1")
                    except SerialException as e:
                        print(
                            "Error initialising data collection {0}".format(e))
                print("Recording...")
                while (is_recording):
                    # Wait for S to be pressed
                    key = readkey.readkey(blocking=blocking_readkey)
                    time.sleep(0.1)
                    if key == 's':
                        is_recording = False
                        if device:
                            try:
                                device.send_string("0")
                                time.sleep(READ_DELAY_SECONDS)
                            except SerialException as e:
                                print("Error stopping data collection {0}".
                                      format(e))
                            del device
                print("Press R to start recording or Q to quit...")