Example #1
0
    def __init__(self):
        self.pose_dat = defaultdict(deque)
        self.pose_dat_lock = threading.Lock()

        self.serial_buffer = ""
        self.serial_buffer_lock = threading.Lock()

        self.rr_lock = threading.Lock()
        self.serial_lock = threading.Lock()

        def factory():
            def settings_factory():
                return [0, 0]

            settings_dict = defaultdict(settings_factory)
            distances_dict = defaultdict(list)
            return (settings_dict, distances_dict)

        self.history_dict = defaultdict(factory)

        self.rr = RoboRealmInterface()
        self.rr.connect()

        self.serial_port = SerialInterface()
        self.serial_port.open("COM16")

        self.rr_thread = threading.Thread(target=self.rr_monitor)
        self.rr_lock.acquire()
        self.rr_thread.start()
        self.serial_thread = threading.Thread(target=self.serial_monitor)
        self.serial_lock.acquire()
        self.serial_thread.start()
 def __init__(self):
     self.serial_port = SerialInterface()
     self.serial_port.open("COM16")
     
     self.serial_buffer = ""
     self.serial_buffer_lock = threading.Lock()    
     self.serial_lock = threading.Lock()
     self.serial_thread = threading.Thread(target=self.serial_monitor)
     self.serial_lock.acquire()
     self.serial_thread.start()    
Example #3
0
 def __init__(self):
     super(DebugerGui, self).__init__()
     self.setupUi(self)
     self.m_clear1.clicked.connect(self.m_result1.clear)
     self.m_clear2.clicked.connect(self.m_result2.clear)
     self.m_send.clicked.connect(self.send_start)
     self.m_stop.clicked.connect(self.send_stop)
     self.interface = SerialInterface()
     self.interface.received.connect(self.show_received)
     self.m_interval.setValidator(QIntValidator(0, 10000))
     self.m_interval.returnPressed.connect(self.send_start)
     self.count1 = -1
     self.count2 = -1
Example #4
0
    def __init__(self, view=None):
        """
        :param view:AppFrame
        :return:Controller
        """

        self.view = view
        self.serial = SerialInterface(view=self.view)
        self.data = []
        self.initiatives = []
        self.members = []
        self.http = HttpInterface()
        self.conf = None
class QuickWriter:
    
    def __init__(self):
        self.serial_port = SerialInterface()
        self.serial_port.open("COM16")
        
        self.serial_buffer = ""
        self.serial_buffer_lock = threading.Lock()    
        self.serial_lock = threading.Lock()
        self.serial_thread = threading.Thread(target=self.serial_monitor)
        self.serial_lock.acquire()
        self.serial_thread.start()    

    def serial_monitor(self):
        while self.serial_lock.locked():
            with self.serial_buffer_lock:
                if len(self.serial_buffer)>0:
                    self.serial_port.write(self.serial_buffer)
                    self.serial_buffer = ""
            self.serial_port.read()
            time.sleep(0.1)
        self.serial_port.close()
        
    def go(self):
        with open('dump.txt','r') as f:
            for line in f:
                with self.serial_buffer_lock:
                    self.serial_buffer = (line+'\n')
                time.sleep(1)
        self.serial_lock.release()
Example #6
0
    def __init__(self):
        self.pose_dat = defaultdict(deque)
        self.pose_dat_lock = threading.Lock()
        
        self.serial_buffer = ""
        self.serial_buffer_lock = threading.Lock()
        
        self.rr_lock = threading.Lock()
        self.serial_lock = threading.Lock()
        
        def factory():
            def settings_factory():
                return [0,0]
            settings_dict = defaultdict(settings_factory)
            distances_dict = defaultdict(list)
            return (settings_dict, distances_dict)
        
        self.history_dict = defaultdict(factory)   
        
        self.rr = RoboRealmInterface()
        self.rr.connect()
        
        self.serial_port = SerialInterface()
        self.serial_port.open("COM16")

        self.rr_thread = threading.Thread(target=self.rr_monitor)
        self.rr_lock.acquire()
        self.rr_thread.start()
        self.serial_thread = threading.Thread(target=self.serial_monitor)
        self.serial_lock.acquire()
        self.serial_thread.start()  
Example #7
0
class DebugerGui(Ui_DebugerGUI, QMainWindow):

    def __init__(self):
        super(DebugerGui, self).__init__()
        self.setupUi(self)
        self.m_clear1.clicked.connect(self.m_result1.clear)
        self.m_clear2.clicked.connect(self.m_result2.clear)
        self.m_send.clicked.connect(self.send_start)
        self.m_stop.clicked.connect(self.send_stop)
        self.interface = SerialInterface()
        self.interface.received.connect(self.show_received)
        self.m_interval.setValidator(QIntValidator(0, 10000))
        self.m_interval.returnPressed.connect(self.send_start)
        self.count1 = -1
        self.count2 = -1

    def closeEvent(self, event):
        self.interface.mif.finishAll()

    def show_received(self, node_id, sequence_num, timestamp, temperature, humidity, illumination):
        string = "node_id: %d, sequence_num: %d, timestamp: %d, temperature: %d, humidity: %d, illumination: %d" %\
                 (node_id, sequence_num, timestamp, temperature, humidity, illumination)
        if node_id == 31:
            if sequence_num != self.count1:
                self.m_result1.append(string)
            if self.count1 >= 0 and sequence_num - self.count1 > 1:
                self.m_result1.append(u"\n丢包!!!\n")
            self.count1 = sequence_num
        elif node_id == 32:
            if sequence_num != self.count2:
                self.m_result2.append(string)
            if self.count2 >= 0 and sequence_num - self.count2 > 1:
                self.m_result2.append(u"\n丢包!!!\n")
            self.count2 = sequence_num

    def send_start(self):
        self.interface.send(CONTROL_START, int(self.m_interval.text()))

    def send_stop(self):
        self.interface.send(CONTROL_STOP)
Example #8
0
    def __init__(self):
        super(ControllerGui, self).__init__()
        self.setupUi(self)
        self.m_clear.clicked.connect(self.clear_plot)
        self.m_send.clicked.connect(self.send_start)
        self.m_stop.clicked.connect(self.send_stop)
        self.interface = SerialInterface()
        self.interface.received.connect(self.show_received)
        self.m_interval.setValidator(QIntValidator(0, 10000))
        self.m_interval.returnPressed.connect(self.send_start)

        brush = QBrush(QColor(255, 255, 255))

        box = QVBoxLayout(self.m_list)

        self.temperature_plot = PlotWidget(self)
        self.temperature_plot.setBackgroundBrush(brush)
        self.temperature_plot.setFixedHeight(300)
        box.addWidget(self.temperature_plot)
        self.temperature_curves = {}

        self.humidity_plot = PlotWidget(self)
        self.humidity_plot.setBackgroundBrush(brush)
        self.humidity_plot.setFixedHeight(300)
        box.addWidget(self.humidity_plot)
        self.humidity_curves = {}

        self.illumination_plot = PlotWidget(self)
        self.illumination_plot.setBackgroundBrush(brush)
        self.illumination_plot.setFixedHeight(300)
        box.addWidget(self.illumination_plot)
        self.illumination_curves = {}
        box.addItem(QSpacerItem(40, 20, QSizePolicy.Maximum, QSizePolicy.Expanding))
        self.m_list.setLayout(box)

        box = QVBoxLayout(self.m_devices)
        box.addItem(QSpacerItem(40, 20, QSizePolicy.Maximum, QSizePolicy.Expanding))
        self.m_devices.setLayout(box)
	self.file = open('result.txt', 'w')
Example #9
0
from SerialInterface import SerialInterface
import time
from Logger import console


def increment(message):
    console.log(message)
    if message == "This is message number 0":
        # console.log("Message correct")
        pass
    else:
        console.log("Message incorrect")


interface = SerialInterface('/dev/tty.usbmodem1421', 115200)
interface.Listen()
interface.OnInput(increment)
message_count = 0

last_time = time.time()
while True:
    cur_time = time.time()
    if cur_time - last_time > 1:
        # print('Recieved %s messages' % (message_count,))
        last_time = cur_time
        interface.Write('This is message number %s' % (message_count, ))
        console.log('Sending message')
Example #10
0
from SerialInterface import SerialInterface
import time
import math
from Logger import console

# interface = SerialInterface('/dev/tty.usbmodem1421', baud=9600)
# interface = SerialInterface('/dev/tty.usbmodem1421', baud=38400)
# interface = SerialInterface('/dev/tty.usbmodem1421', baud=57600)
interface = SerialInterface('/dev/tty.usbmodem1421', baud=115200)
interface.listen()
time.sleep(1)

console.log('Starting test')
for i in range(0, 500):
    interface.write('Number %d' % (i, ))

interface.flush()

input('Waiting for completion...')
interface.stop()
Example #11
0
class MotionTuner:

    ordered_ids = [
        "2B4E", "7D78", "8B46", "C806", "4177", "0A0B", "3B49", "028C", "1F08",
        "EEB0", "A649", "A5B5", "F60A", "B944", "3405", "43BA", "6648", "1B4B",
        "C24B", "4DB0"
    ]
    last_direction = 0
    droplet_pixel_radius = 36.0
    last_direction_dict = defaultdict(lambda: 0)

    def __init__(self):
        self.pose_dat = defaultdict(deque)
        self.pose_dat_lock = threading.Lock()

        self.serial_buffer = ""
        self.serial_buffer_lock = threading.Lock()

        self.rr_lock = threading.Lock()
        self.serial_lock = threading.Lock()

        def factory():
            def settings_factory():
                return [0, 0]

            settings_dict = defaultdict(settings_factory)
            distances_dict = defaultdict(list)
            return (settings_dict, distances_dict)

        self.history_dict = defaultdict(factory)

        self.rr = RoboRealmInterface()
        self.rr.connect()

        self.serial_port = SerialInterface()
        self.serial_port.open("COM16")

        self.rr_thread = threading.Thread(target=self.rr_monitor)
        self.rr_lock.acquire()
        self.rr_thread.start()
        self.serial_thread = threading.Thread(target=self.serial_monitor)
        self.serial_lock.acquire()
        self.serial_thread.start()

    def rr_monitor(self):
        while self.rr_lock.locked():
            with self.pose_dat_lock:
                for k, v in self.rr.get_robot_positions().items():
                    self.pose_dat[k].append(v)
                    if (len(self.pose_dat[k]) > 300):
                        self.pose_dat[k].popleft()
#                for robot_id in self.pose_dat.keys():
#                   print('\t{0}: {1}'.format(robot_id, self.pose_dat[robot_id][-1]))
#                print()
            self.rr.wait_image()
        self.rr.disconnect()

    def serial_monitor(self):
        while self.serial_lock.locked():
            with self.serial_buffer_lock:
                if len(self.serial_buffer) > 0:
                    self.serial_port.write(self.serial_buffer)
                    self.serial_buffer = ""
            self.serial_port.read()
            time.sleep(0.1)
        self.serial_port.close()

    def calculate_dist_per_step(self):
        for robot_id in self.pose_dat.keys():
            last_dir = self.last_direction_dict[robot_id]
            if last_dir == 0:
                continue
            elif last_dir > 2:
                distance = 0
                pose_hist = self.pose_dat[robot_id]
                #                print(pose_hist)
                #                time.sleep(30)
                for i in range(1, len(self.pose_dat[robot_id])):
                    deltaTheta = pose_hist[i][2] - pose_hist[i - 1][2]
                    if deltaTheta > 180:
                        deltaTheta = deltaTheta - 360
                    elif deltaTheta < -180:
                        deltaTheta = deltaTheta + 360
                    distance += deltaTheta
#                print('{0}: {1}'.format(robot_id, distance))
            else:
                distance = 0
                pose_hist = self.pose_dat[robot_id]
                for i in range(1, len(self.pose_dat[robot_id])):
                    distance += hypot(pose_hist[i][0] - pose_hist[i - 1][0],
                                      pose_hist[i][1] - pose_hist[i - 1][1])
            self.history_dict[robot_id][1][last_dir].append(distance)

    def get_rand_dir(self):
        rand_int = random.randint(0, 7)
        if rand_int < 3:
            return 1
        elif rand_int < 6:
            return 2
        else:
            return (rand_int - 3)

    def calculate_adjust_response(self, bot_id):
        (center, radius, residual, sign) = self.lsq_dat[bot_id]
        direction = self.last_direction_dict[bot_id]
        if direction > 2:
            return 0
        if radius < 10:
            #We haven't really moved. Do nothing.
            return 0
        elif radius > 80000:
            #We're basically going straight. Call it good.
            return 0
        else:
            if sign < 0:
                return 1
            elif sign > 0:
                return 2
            else:
                return 0

    def calculate_desired_directions(self):
        forces_dict = defaultdict(lambda: np.array([0.0, 0.0]))
        for botId in self.ordered_ids:
            if (len(self.pose_dat[botId]) <= 0):
                continue
            botPos = np.array(
                [self.pose_dat[botId][-1][0], self.pose_dat[botId][-1][1]])
            #            print('{0} @ {1}'.format(botId, botPos))

            bl_diff = (botPos / self.droplet_pixel_radius) + np.array(
                [1.0, 1.0])
            tr_diff = ((np.array([1000.0, 1000.0]) - botPos) /
                       self.droplet_pixel_radius) + np.array([1.0, 1.0])
            bl_wall_force = 1.8 / (bl_diff**1.0)
            tr_wall_force = 1.8 / (tr_diff**1.0)
            wall_forces = bl_wall_force - tr_wall_force

            forces_dict[botId] += wall_forces
            #            print('\tWALLS: {0}'.format(wall_forces))

            for otherBotId in reversed(self.ordered_ids):
                if botId is otherBotId:
                    break
                if len(self.pose_dat[otherBotId]) <= 0:
                    continue

                otherBotPos = np.array([
                    self.pose_dat[otherBotId][-1][0],
                    self.pose_dat[otherBotId][-1][1]
                ])

                diffVec = (botPos - otherBotPos) / self.droplet_pixel_radius
                r = np.linalg.norm(diffVec)
                forceVec = ((1.5 * diffVec) / (r**3))
                #                print('\t({0}, {1}): {2}  \t{3}  \t{4}'.format(botId, otherBotId, diffVec, r, forceVec))

                forces_dict[botId] += forceVec
                forces_dict[otherBotId] -= forceVec
        direction_dict = defaultdict()
        for botId in self.ordered_ids:
            delta_theta = 0.0
            (r, theta) = (hypot(*forces_dict[botId]),
                          degrees(np.arctan2(*(forces_dict[botId][::-1]))))
            if r < 0.1:
                direction_dict[botId] = self.get_rand_dir()
            elif len(self.pose_dat[botId]) <= 0:
                direction_dict[botId] = self.get_rand_dir()
            else:
                delta_theta = CustomMaths.pretty_angle(
                    (theta - 90) - self.pose_dat[botId][-1][2])
                if abs(delta_theta) <= 50:
                    direction_dict[botId] = 1  #straight forward
                elif abs(delta_theta) >= 130:
                    direction_dict[botId] = 2  #straight backward
                elif delta_theta > 0:
                    direction_dict[botId] = 4  #turn left
                elif delta_theta < 0:
                    direction_dict[botId] = 3  #turn right
#            print('{0}: ({1}, {2}, {3}): {4}'.format(botId, r, theta, delta_theta, direction_dict[botId]))
        return direction_dict

    def get_per_robot_command(self, bot_id, direction):
        value = (96 + (direction << 2))
        if (self.lsq_dat[bot_id]
                is not None) and self.last_direction_dict[bot_id] is not 0:
            adjust = self.calculate_adjust_response(bot_id)
            value += adjust
            if adjust is 1:
                self.history_dict[bot_id][0][
                    self.last_direction_dict[bot_id]][0] -= 10
                self.history_dict[bot_id][0][
                    self.last_direction_dict[bot_id]][1] += 10
            elif adjust is 2:
                self.history_dict[bot_id][0][
                    self.last_direction_dict[bot_id]][0] += 10
                self.history_dict[bot_id][0][
                    self.last_direction_dict[bot_id]][1] -= 10
        return chr(value)

    def send_message(self):
        direction_dict = self.calculate_desired_directions()
        commands = [
            self.get_per_robot_command(bot_id, direction_dict[bot_id])
            for bot_id in self.ordered_ids
        ]
        self.last_direction_dict = direction_dict
        with self.serial_buffer_lock:
            self.serial_buffer = 'msg {0}{1}{2}{3}{4}{5}{6}{7}{8}{9}{10}{11}{12}{13}{14}{15}{16}{17}{18}{19}'.format(
                *commands)

    def main_loop(self):
        self.lsq_dat = defaultdict(lambda: (0, 0, 0, 0))

        with self.pose_dat_lock:
            for robot_id in self.pose_dat.keys():
                try:
                    self.lsq_dat[robot_id] = CustomMaths.lsq_circle_fit(
                        np.array(self.pose_dat[robot_id]))
                except TypeError:
                    continue
            self.calculate_dist_per_step()

            self.send_message()
            self.pose_dat = defaultdict(deque)
            self.lsq_dat = defaultdict(lambda: (0, 0, 0, 0))


#        for bot in self.ordered_ids:
#            print(bot,end='')
#            for dir in [1,2,3,4]:
#                print('\t',end='')
#                print(self.history_dict[bot][1][dir])

    def clean_up(self):
        print('{')
        for bot in self.ordered_ids:
            print('{{{0}, '.format(bot), end='')
            for dir in [1, 2]:
                print('{{{0}, {1}}}, '.format(*self.history_dict[bot][0][dir]),
                      end='')
            for dir in [1, 2, 3, 4]:
                print('{', end='')
                for dist in self.history_dict[bot][1][dir]:
                    print('{0}, '.format(dist), end='')
                print('}, ', end='')
            print('}, ')
        print('}')
        self.rr_lock.release()
        self.rr_thread.join()
        self.serial_lock.release()
        self.serial_thread.join()

    def main(self):
        with self.serial_buffer_lock:
            self.serial_buffer = 'cmd reset'
        time.sleep(1)
        try:
            while True:
                for _ in range(30):
                    time.sleep(1)
                self.main_loop()
        except:
            self.clean_up()
            raise
Example #12
0
        cv2.imwrite(
            'snapshot_{0:%Y%m%d_%H%M%S}.jpg'.format(datetime.datetime.now()),
            img)

    # キャプチャ終了
    cap.release()

    return result


##############
# メイン関数 #
##############
if __name__ == '__main__':
    # bluetooth通信用COMポートを開通する
    si = SerialInterface()
    si.open(port, baud, None)

    # 要求待ち受けのループ
    while True:
        try:
            # クライアントから要求パケットを受信する(受信するまでブロックすることに注意)
            command, parameter = si.read()
            print("(command, parameter) = ", (command, parameter))

            # # parameterを解読し色判定対象のピクセル座標のリストを作る
            # points, errmsg = decodePacket(command, parameter)

            # # 色判定結果から応答パケットを作る
            # if points is not None:
            #     # 座標色応答
        cv2.imwrite(
            'snapshot_{0:%Y%m%d_%H%M%S}.jpg'.format(datetime.datetime.now()),
            img)

    # キャプチャ終了
    cap.release()

    return result


##############
# メイン関数 #
##############
if __name__ == '__main__':
    # bluetooth通信用COMポートを開通する
    si = SerialInterface()
    si.open(port, baud, None)

    # 要求待ち受けのループ
    while True:
        try:
            # クライアントから要求パケットを受信する(受信するまでブロックすることに注意)
            command, parameter = si.read()
            print("(command, parameter) = ", (command, parameter))

            # parameterを解読し色判定対象のピクセル座標のリストを作る
            points, errmsg = decodePacket(command, parameter)

            # 色判定結果から応答パケットを作る
            if points is not None:
                # 座標色応答
Example #14
0
def main():
    print "[+] Starting bot..."

    # Read the config file
    print "[+] Reading config file..."
    config = ConfigParser.ConfigParser()
    config.read([os.path.expanduser("./config")])

    # Read data
    bot_name = config.get("bot", "name")
    bot_token = config.get("bot", "token")
    user_id = config.get("user", "allowed")

    # Last mssg id:
    last_id = int(load_last_id())
    print "[+] Last id: %d" % last_id

    # Configure regex
    regex = re.compile("[%s]" % re.escape(string.punctuation))

    # Create bot
    print "[+] Connecting bot..."
    bot = TelegramBot(bot_token)
    bot.update_bot_info().wait()
    print "\tBot connected! Bot name: %s" % bot.username

    # Connect to hardware
    interface = SerialInterface()
    interface.connect("/dev/ttyUSB0", 9600)

    # Send special keyboard:
    send_keyboard(bot, user_id)

    while True:
        try:
            updates = bot.get_updates(offset=last_id).wait()

            for update in updates:
                id = update.message.message_id
                update_id = update.update_id
                user = update.message.sender

                chat_id = update.message.chat.id
                text = update.message.text

                if int(update_id) > last_id:
                    last_id = update_id
                    save_last_id(last_id)
                    save_log(id, update_id, chat_id, text)

                    # text = regex.sub('', text)
                    if text:
                        words = text.split()

                        for i, word in enumerate(words):
                            # Process commands:
                            if word == "/start":
                                print "New user started the app: " + str(user)
                                send_keyboard(bot, chat_id)
                            elif word == "/flag":
                                if words[i + 1] == "up":
                                    interface.sendMove(90)
                                    break
                                elif words[i + 1] == "down":
                                    interface.sendMove(0)
                                    break
                                else:
                                    bot.send_message(chat_id, "Bad syntax!")
                                    break

                            # Restricted API
                            if int(user_id) == user.id:
                                if word == "/move":
                                    try:
                                        interface.sendMove(int(words[i + 1]))
                                        break
                                    except Exception, e:
                                        print e

        except (KeyboardInterrupt, SystemExit):
            print "\nkeyboardinterrupt caught (again)"
            print "\n...Program Stopped Manually!"
            raise
Example #15
0
class ControllerGui(Ui_ControllerGUI, QMainWindow):

    def __init__(self):
        super(ControllerGui, self).__init__()
        self.setupUi(self)
        self.m_clear.clicked.connect(self.clear_plot)
        self.m_send.clicked.connect(self.send_start)
        self.m_stop.clicked.connect(self.send_stop)
        self.interface = SerialInterface()
        self.interface.received.connect(self.show_received)
        self.m_interval.setValidator(QIntValidator(0, 10000))
        self.m_interval.returnPressed.connect(self.send_start)

        brush = QBrush(QColor(255, 255, 255))

        box = QVBoxLayout(self.m_list)

        self.temperature_plot = PlotWidget(self)
        self.temperature_plot.setBackgroundBrush(brush)
        self.temperature_plot.setFixedHeight(300)
        box.addWidget(self.temperature_plot)
        self.temperature_curves = {}

        self.humidity_plot = PlotWidget(self)
        self.humidity_plot.setBackgroundBrush(brush)
        self.humidity_plot.setFixedHeight(300)
        box.addWidget(self.humidity_plot)
        self.humidity_curves = {}

        self.illumination_plot = PlotWidget(self)
        self.illumination_plot.setBackgroundBrush(brush)
        self.illumination_plot.setFixedHeight(300)
        box.addWidget(self.illumination_plot)
        self.illumination_curves = {}
        box.addItem(QSpacerItem(40, 20, QSizePolicy.Maximum, QSizePolicy.Expanding))
        self.m_list.setLayout(box)

        box = QVBoxLayout(self.m_devices)
        box.addItem(QSpacerItem(40, 20, QSizePolicy.Maximum, QSizePolicy.Expanding))
        self.m_devices.setLayout(box)
	self.file = open('result.txt', 'w')

    def closeEvent(self, event):
	self.file.close()
        self.interface.mif.finishAll()

    def show_received(self, node_id, sequence_num, timestamp, temperature, humidity, illumination):
        result = "ID:" + str(node_id) + " SeqNo:" + str(sequence_num) + " temperature:" + str(temperature) + \
              " humidity:" + str(humidity) + " illumination:" + str(illumination) + " time:" + str(timestamp) + "\n"
        self.file.write(result)
        print("ID:" + str(node_id) + " SeqNo:" + str(sequence_num))
        
	try:
            temperature_curve = self.temperature_curves[str(node_id)]
            humidity_curve = self.humidity_curves[str(node_id)]
            illumination_curve = self.illumination_curves[str(node_id)]
        except KeyError:
            temperature_curve = self.temperature_plot.plot([], [])
            humidity_curve = self.humidity_plot.plot([], [])
            illumination_curve = self.illumination_plot.plot([], [])
            self.temperature_curves[str(node_id)] = temperature_curve
            self.humidity_curves[str(node_id)] = humidity_curve
            self.illumination_curves[str(node_id)] = illumination_curve

            box = self.m_devices.layout()

            device_item = DeviceItem(self.m_devices, node_id)
            device_item.colorChanged.connect(self.set_device_color)
            self.set_device_color(node_id, device_item.color)
            device_item.showChanged.connect(self.change_device_show)
            device_item.temperatureChanged.connect(self.change_device_temperature)
            device_item.humidityChanged.connect(self.change_device_humidity)
            device_item.illuminationChanged.connect(self.change_device_illumination)

            box.insertWidget(box.count() - 1, device_item)
            self.m_aside.setFixedWidth(device_item.width())

        data = temperature_curve.getData()
        data_x, temperature_y = list(data[0]), list(data[1])
        data_x.append(timestamp / 1000.0)
        temperature_y.append(temperature)
        temperature_curve.setData(data_x, temperature_y)

        data = humidity_curve.getData()
        data_x, humidity_y = list(data[0]), list(data[1])
        data_x.append(timestamp / 1000.0)
        humidity_y.append(humidity)
        humidity_curve.setData(data_x, humidity_y)

        data = illumination_curve.getData()
        data_x, illumination_y = list(data[0]), list(data[1])
        data_x.append(timestamp / 1000.0)
        illumination_y.append(illumination)
        illumination_curve.setData(data_x, illumination_y)

    def send_start(self):
        self.interface.send(CONTROL_START, int(self.m_interval.text()))

    def send_stop(self):
        self.interface.send(CONTROL_STOP)

    def clear_plot(self):
        for key in self.temperature_curves:
            self.temperature_curves[key].setData([], [])
            self.humidity_curves[key].setData([], [])
            self.illumination_curves[key].setData([], [])

    def set_device_color(self, node_id, color):
        self.temperature_curves[str(node_id)].setPen(color)
        self.humidity_curves[str(node_id)].setPen(color)
        self.illumination_curves[str(node_id)].setPen(color)

    def change_device_show(self, node_id, check, t_check, h_check, i_check):
        if check:
            self.change_device_temperature(node_id, t_check)
            self.change_device_humidity(node_id, h_check)
            self.change_device_illumination(node_id, i_check)
        else:
            self.temperature_curves[str(node_id)].hide()
            self.humidity_curves[str(node_id)].hide()
            self.illumination_curves[str(node_id)].hide()

    def change_device_temperature(self, node_id, check):
        if check:
            self.temperature_curves[str(node_id)].show()
        else:
            self.temperature_curves[str(node_id)].hide()

    def change_device_humidity(self, node_id, check):
        if check:
            self.humidity_curves[str(node_id)].show()
        else:
            self.humidity_curves[str(node_id)].hide()

    def change_device_illumination(self, node_id, check):
        if check:
            self.illumination_curves[str(node_id)].show()
        else:
            self.illumination_curves[str(node_id)].hide()
Example #16
0
 def __init__(self):
     super(DevTool, self).__init__()
     self.ser = SerialInterface()
     self.log = DataLog(LOG_PATH)
     self.initUI()
Example #17
0
class DevTool(QtWidgets.QWidget):

    def __init__(self):
        super(DevTool, self).__init__()
        self.ser = SerialInterface()
        self.log = DataLog(LOG_PATH)
        self.initUI()

    def initUI(self):

        self.console_view = ConsoleView()
        self.dv = DisplayView(SCREENSHOT_PATH)
        self.dv.hide()
        self.pv = PacketView(EXPORT_PATH)

        self.checkbox = QtWidgets.QCheckBox('Pause')
        self.checkbox.stateChanged.connect(self.console_view.toogle_pause)

        self.port_select = QtWidgets.QComboBox()

        for port in self.ser.get_ports():
            self.port_select.addItem(port)

        self.connect_button = QtWidgets.QPushButton('Connect')
        self.connect_button.setCheckable(True)
        self.connect_button.clicked[bool].connect(self.connect_clicked)

        self.pixel_label = QtWidgets.QLabel()
        self.pixel_label.setText('X: 0, Y: 0')
        self.pixel_label.hide()

        self.save_display_button = QtWidgets.QPushButton('Save image')
        self.save_display_button.clicked.connect(self.dv.save_view_to_file)
        self.save_display_button.hide()

        self.display_hbox = QtWidgets.QHBoxLayout()
        self.display_hbox.addWidget(self.pixel_label)
        self.display_hbox.addWidget(self.save_display_button)

        display_vbox = QtWidgets.QVBoxLayout()
        display_vbox.addWidget(self.dv)
        display_vbox.addLayout(self.display_hbox)
        display_vbox.addStretch(1)

        hbox = QtWidgets.QHBoxLayout()
        hbox.addLayout(display_vbox)
        hbox.addWidget(self.console_view)

        connect_box = QtWidgets.QHBoxLayout()
        connect_box.addWidget(self.port_select)
        connect_box.addWidget(self.connect_button)
        connect_box.addStretch(1)
        connect_box.addWidget(self.checkbox)

        clear_packets_button = QtWidgets.QPushButton('Clear')
        clear_packets_button.clicked.connect(self.pv.setRowCount)
        export_packets_button = QtWidgets.QPushButton('Export')
        export_packets_button.clicked.connect(
            lambda: self.pv.export_to_csv('packets'))

        packet_btn_box = QtWidgets.QHBoxLayout()
        packet_btn_box.addWidget(clear_packets_button)
        packet_btn_box.addWidget(export_packets_button)
        packet_btn_box.addStretch(1)

        vbox = QtWidgets.QVBoxLayout()
        vbox.addLayout(connect_box)

        vbox.addLayout(hbox)

        vbox.addWidget(self.pv)
        vbox.addLayout(packet_btn_box)

        self.setLayout(vbox)

        self.resize(1050, 600)
        self.center()
        self.setWindowTitle('SillyCat Development Tool')
        self.setWindowIcon(QtGui.QIcon(DEV_ICON))
        self.show()

        self.ser.new_vram.connect(self.dv.update_display_view)
        self.ser.new_vram.connect(self.show_display_widgets)
        self.ser.new_pck.connect(self.pv.update_packet_view)
        self.ser.new_stream.connect(self.console_view.update_console_view)
        self.ser.new_stream.connect(self.print_text)
        self.ser.new_stream.connect(self.log.handle_signal)
        self.dv.new_pixel.connect(self.update_pixel_text)

    def connect_clicked(self, pressed):
        if pressed:
            port = str(self.port_select.currentText())

            try:
                if self.ser.open_port(port, BAUDRATE):
                    self.ser.start()
                    self.console_view.appendHtml(
                        '<b>Connected to ' + port + '</b>')
                else:
                    self.connect_button.setChecked(False)
                    self.console_view.appendHtml(
                        '<b>Failed to open interface on ' + port + '</b>')
            except:
                self.connect_button.setChecked(False)
                self.console_view.appendHtml(
                    '<b>Exception when opening interface on ' + port + '</b>')

        else:
            self.ser.stop()
            self.console_view.appendHtml('<b>Disconnected<b>')

    def show_display_widgets(self, image_data):
        if self.save_display_button.isHidden():
            self.save_display_button.show()

        if self.pixel_label.isHidden():
            self.pixel_label.show()

    def update_pixel_text(self, point):

        self.dv.set_pixel(int(point.x()), int(point.y()))

        self.pixel_label.setText(
            'X: ' + str(point.x()) + ',Y: ' + str(point.y()))

    def closeEvent(self, event):
        self.ser.stop()
        event.accept()

    def center(self):
        qr = self.frameGeometry()
        cp = QtWidgets.QDesktopWidget().availableGeometry().center()
        qr.moveCenter(cp)
        self.move(qr.topLeft())

    def print_text(self, text):
        print(text)
Example #18
0
            fillcolor=stimulus['Color'])

        SoundStimuliList[stimulus_name].initLocalizedSound(
            center=stimulus['CenterPosition'],
            width=stimulus['Modulation']['Width'],
            trackLength=VirtualTrackLength,
            maxGain=stimulus['BaselineGain'],
            minGain=stimulus['Modulation']['CutoffGain'])
        SoundStimuliList[stimulus_name].change_gain(
            -90.0)  # start off turned off

    time.sleep(1.0)

from SerialInterface import SerialInterface

Interface = SerialInterface(SerialPort=args.serial_port)

if 'GPIO' in Config:
    for gpio_label, gpio_config in Config['GPIO'].items():
        Interface.add_gpio(gpio_label, gpio_config)

# Create a GPIO pin to use to trigger the lick sensor
Interface.add_gpio('LickTrigger', {
    'Number': 1,
    'Type': 'Output',
    'Mirror': True
})

from RewardZone import ClassicalRewardZone, OperantRewardZone

RewardsList = []
Example #19
0
class MainApp:
    hdmiActive = True
    shutdownRequested = False
    shutdownShellCmd = ""
    lastStateUpdate = 0

    inetMgr = InternetManager()
    audioMgr = AudioManager()
    usbManager = UsbManager()
    mpdClient = MopidyClient()
    serialIf = SerialInterface()

    def __init__(self):
        pass

    def requestShutdown(self, shellCmd):
        self.shutdownRequested = True
        self.shutdownShellCmd = shellCmd

    def handleShutdownRequest(self, signal, frame):
        self.requestShutdown("")

    def run(self):
        signal.signal(signal.SIGINT, self.handleShutdownRequest)
        signal.signal(signal.SIGTERM, self.handleShutdownRequest)

        self.usbManager.start()
        self.inetMgr.start()
        self.audioMgr.start()

        while not self.shutdownRequested:
            start = time.time()
            self.loop()
            end = time.time()
            delta = end - start
            time.sleep(max(0, 0.3 - delta))

        self.mpdClient.saveStateFile()
        self.mpdClient.stop()

        self.audioMgr.stop()
        self.inetMgr.stop()
        self.usbManager.stop()

        if self.shutdownShellCmd != "":
            call(self.shutdownShellCmd, shell=True)

    def shutdownHdmi(self):
        if self.inetMgr.isOnline() and self.hdmiActive:
            self.hdmiActive = False
            call("/usr/bin/tvservice -o", shell=True)

    def loop(self):
        try:
            messages = self.serialIf.read()
            for msg in messages:
                #print(str(msg))
                for (k, v) in msg.items():
                    if k == "volume":
                        self.audioMgr.setAudioVolume(v)
                    elif k == "playlist":
                        self.mpdClient.loadPlaylist(v)
                    elif k == "stop":
                        self.mpdClient.stop()
                    elif k == "togglePlayPause":
                        self.mpdClient.togglePlayPause()
                    elif k == "skipPrevious":
                        self.mpdClient.skipToPreviousTrack(v)
                    elif k == "skipNext":
                        self.mpdClient.skipToNextTrack(v)
                    elif k == "skipToStart":
                        self.mpdClient.skipToStart()
                    elif k == "skipTo":
                        self.mpdClient.skipToTrack(v)
                    elif k == "seek":
                        self.mpdClient.seek(v)
                    elif k == "shutdown":
                        self.requestShutdown("sudo shutdown 0")
                    elif k == "reboot":
                        self.requestShutdown("sudo reboot 0")
                    elif k == "wifiSsid":
                        self.inetMgr.setWifiSsid(v)
                    elif k == "wifiKey":
                        self.inetMgr.setWifiKey(v)
                    elif k == "spotifyUser":
                        self.mpdClient.setSpotifyUser(v)
                    elif k == "spotifyPassword":
                        self.mpdClient.setSpotifyPassword(v)
                    elif k == "spotifyClientId":
                        self.mpdClient.setSpotifyClientId(v)
                    elif k == "spotifyClientSecret":
                        self.mpdClient.setSpotifyClientSecret(v)
        except Exception as e:
            print(str(e))

        if time.time() - self.lastStateUpdate > 0.66:
            self.lastStateUpdate = time.time()
            try:
                dict = {}
                dict["online"] = self.inetMgr.isOnline()
                dict.update(self.mpdClient.updateStatus())
                self.serialIf.write(dict)
                self.shutdownHdmi()
            except Exception as e:
                print(str(e))

        self.mpdClient.disconnect()
Example #20
0
rr_lock = threading.Lock()
serial_lock = threading.Lock()

def factory():
    def settings_factory():
        return [0,0]
    settings_dict = defaultdict(settings_factory)
    distances_dict = defaultdict(list)
    return (settings_dict, distances_dict)

history_dict = defaultdict(factory)

rr = RoboRealmInterface()
rr.connect()
serial_port = SerialInterface()
if not serial_port.open("COM16"):
    print('Error opening serial port %s'%"COM16")
    
def rr_monitor():
    HISTORY_LENGTH = 300        
    
    while rr_lock.locked():
        with pose_dat_lock:
            for k, v in rr.get_robot_positions().items():
                pose_dat[k].append(v)
                if(len(pose_dat[k])>HISTORY_LENGTH):
                    pose_dat[k].popleft()
            for robot_id in pose_dat.keys():
                print('\t{0}: {1}'.format(robot_id, pose_dat[robot_id][-1]))
            print()
Example #21
0
class MotionTuner:
    
    ordered_ids = ["2B4E", "7D78", "8B46", "C806", "4177", "0A0B", "3B49", 
                   "028C", "1F08", "EEB0", "A649", "A5B5", "F60A", "B944", 
                   "3405", "43BA", "6648", "1B4B", "C24B", "4DB0"]
    last_direction = 0
    droplet_pixel_radius=36.0
    last_direction_dict = defaultdict(lambda: 0)             
    
    def __init__(self):
        self.pose_dat = defaultdict(deque)
        self.pose_dat_lock = threading.Lock()
        
        self.serial_buffer = ""
        self.serial_buffer_lock = threading.Lock()
        
        self.rr_lock = threading.Lock()
        self.serial_lock = threading.Lock()
        
        def factory():
            def settings_factory():
                return [0,0]
            settings_dict = defaultdict(settings_factory)
            distances_dict = defaultdict(list)
            return (settings_dict, distances_dict)
        
        self.history_dict = defaultdict(factory)   
        
        self.rr = RoboRealmInterface()
        self.rr.connect()
        
        self.serial_port = SerialInterface()
        self.serial_port.open("COM16")

        self.rr_thread = threading.Thread(target=self.rr_monitor)
        self.rr_lock.acquire()
        self.rr_thread.start()
        self.serial_thread = threading.Thread(target=self.serial_monitor)
        self.serial_lock.acquire()
        self.serial_thread.start()  
                             
    
    def rr_monitor(self):         
        while self.rr_lock.locked():
            with self.pose_dat_lock:
                for k, v in self.rr.get_robot_positions().items():
                    self.pose_dat[k].append(v)
                    if(len(self.pose_dat[k])>300):
                        self.pose_dat[k].popleft()
#                for robot_id in self.pose_dat.keys():
#                   print('\t{0}: {1}'.format(robot_id, self.pose_dat[robot_id][-1]))
#                print()
            self.rr.wait_image()
        self.rr.disconnect()
        
    def serial_monitor(self):
        while self.serial_lock.locked():
            with self.serial_buffer_lock:
                if len(self.serial_buffer)>0:
                    self.serial_port.write(self.serial_buffer)
                    self.serial_buffer = ""
            self.serial_port.read()
            time.sleep(0.1)
        self.serial_port.close()
            
            
    def calculate_dist_per_step(self):
        for robot_id in self.pose_dat.keys():
            last_dir = self.last_direction_dict[robot_id]
            if last_dir==0:
                continue        
            elif last_dir>2:
                distance = 0
                pose_hist = self.pose_dat[robot_id]
#                print(pose_hist)
#                time.sleep(30)
                for i in range(1,len(self.pose_dat[robot_id])):
                    deltaTheta = pose_hist[i][2]-pose_hist[i-1][2]
                    if deltaTheta>180:
                        deltaTheta = deltaTheta-360
                    elif deltaTheta<-180:
                        deltaTheta = deltaTheta+360
                    distance += deltaTheta
#                print('{0}: {1}'.format(robot_id, distance))
            else:
                distance = 0
                pose_hist = self.pose_dat[robot_id]
                for i in range(1,len(self.pose_dat[robot_id])):
                    distance += hypot(pose_hist[i][0]-pose_hist[i-1][0],pose_hist[i][1]-pose_hist[i-1][1])
            self.history_dict[robot_id][1][last_dir].append(distance)
            
            
    def get_rand_dir(self):
        rand_int = random.randint(0,7)
        if rand_int<3:
            return 1
        elif rand_int<6:
            return 2
        else:
            return (rand_int-3)
            
        
    def calculate_adjust_response(self, bot_id):
        (center, radius, residual, sign) = self.lsq_dat[bot_id]
        direction = self.last_direction_dict[bot_id]
        if direction>2:
            return 0
        if radius<10:
            #We haven't really moved. Do nothing.
            return 0
        elif radius>80000:
            #We're basically going straight. Call it good.
            return 0
        else:
            if sign<0:
                return 1
            elif sign>0:
                return 2
            else:
                return 0

    def calculate_desired_directions(self):
        forces_dict = defaultdict(lambda: np.array([0.0,0.0]))
        for botId in self.ordered_ids:
            if(len(self.pose_dat[botId])<=0):
                continue
            botPos = np.array([self.pose_dat[botId][-1][0], 
                               self.pose_dat[botId][-1][1]])
#            print('{0} @ {1}'.format(botId, botPos))       
        
            bl_diff = (botPos/self.droplet_pixel_radius)+np.array([1.0,1.0])
            tr_diff = ((np.array([1000.0, 1000.0])-botPos)/self.droplet_pixel_radius)+np.array([1.0,1.0])
            bl_wall_force = 1.8/(bl_diff**1.0)
            tr_wall_force = 1.8/(tr_diff**1.0)
            wall_forces = bl_wall_force-tr_wall_force

            forces_dict[botId]+=wall_forces                                    
#            print('\tWALLS: {0}'.format(wall_forces))
                        
            for otherBotId in reversed(self.ordered_ids):
                if botId is otherBotId:
                    break
                if len(self.pose_dat[otherBotId])<=0:
                    continue
                
                otherBotPos = np.array([self.pose_dat[otherBotId][-1][0], 
                                        self.pose_dat[otherBotId][-1][1]])
                    
                diffVec = (botPos - otherBotPos)/self.droplet_pixel_radius
                r = np.linalg.norm(diffVec)
                forceVec = ((1.5*diffVec)/(r**3))
#                print('\t({0}, {1}): {2}  \t{3}  \t{4}'.format(botId, otherBotId, diffVec, r, forceVec))
                
                forces_dict[botId] += forceVec
                forces_dict[otherBotId] -= forceVec
        direction_dict = defaultdict()
        for botId in self.ordered_ids:
            delta_theta = 0.0
            (r, theta) = (hypot(*forces_dict[botId]), degrees(np.arctan2(*(forces_dict[botId][::-1]))))
            if r<0.1:
                direction_dict[botId] = self.get_rand_dir()
            elif len(self.pose_dat[botId])<=0:
                direction_dict[botId] = self.get_rand_dir()
            else:
                delta_theta = CustomMaths.pretty_angle((theta-90)-self.pose_dat[botId][-1][2])
                if abs(delta_theta)<=50:
                    direction_dict[botId] = 1 #straight forward
                elif abs(delta_theta)>=130:
                    direction_dict[botId] = 2 #straight backward
                elif delta_theta>0:
                    direction_dict[botId] = 4 #turn left
                elif delta_theta<0:
                    direction_dict[botId] = 3 #turn right
#            print('{0}: ({1}, {2}, {3}): {4}'.format(botId, r, theta, delta_theta, direction_dict[botId]))
        return direction_dict            
    
    def get_per_robot_command(self, bot_id, direction):
        value = (96+(direction<<2))
        if (self.lsq_dat[bot_id] is not None) and self.last_direction_dict[bot_id] is not 0:
            adjust = self.calculate_adjust_response(bot_id)
            value += adjust
            if adjust is 1:
                self.history_dict[bot_id][0][self.last_direction_dict[bot_id]][0] -= 10
                self.history_dict[bot_id][0][self.last_direction_dict[bot_id]][1] += 10                        
            elif adjust is 2:
                self.history_dict[bot_id][0][self.last_direction_dict[bot_id]][0] += 10
                self.history_dict[bot_id][0][self.last_direction_dict[bot_id]][1] -= 10                              
        return chr(value)    

    def send_message(self):
        direction_dict = self.calculate_desired_directions()
        commands = [self.get_per_robot_command(bot_id, direction_dict[bot_id]) for bot_id in self.ordered_ids]
        self.last_direction_dict = direction_dict
        with self.serial_buffer_lock:
            self.serial_buffer = 'msg {0}{1}{2}{3}{4}{5}{6}{7}{8}{9}{10}{11}{12}{13}{14}{15}{16}{17}{18}{19}'.format(*commands)        

    def main_loop(self):
        self.lsq_dat = defaultdict(lambda: (0,0,0,0))
    
        with self.pose_dat_lock:
            for robot_id in self.pose_dat.keys():
                try:
                    self.lsq_dat[robot_id] = CustomMaths.lsq_circle_fit(np.array(self.pose_dat[robot_id]))
                except TypeError:
                    continue
            self.calculate_dist_per_step()
            
            self.send_message()           
            self.pose_dat = defaultdict(deque)
            self.lsq_dat = defaultdict(lambda: (0,0,0,0))
#        for bot in self.ordered_ids:
#            print(bot,end='')
#            for dir in [1,2,3,4]:
#                print('\t',end='')
#                print(self.history_dict[bot][1][dir])                

    def clean_up(self):
        print('{')
        for bot in self.ordered_ids:
            print('{{{0}, '.format(bot), end='')
            for dir in [1,2]:
                print('{{{0}, {1}}}, '.format(*self.history_dict[bot][0][dir]), end='')
            for dir in [1,2,3,4]:
                print('{', end='')
                for dist in self.history_dict[bot][1][dir]:
                    print('{0}, '.format(dist), end='')
                print('}, ', end='')
            print('}, ')
        print('}')
        self.rr_lock.release()
        self.rr_thread.join()
        self.serial_lock.release()        
        self.serial_thread.join()        

    def main(self):
        with self.serial_buffer_lock:
            self.serial_buffer = 'cmd reset'
        time.sleep(1)
        try:     
            while True:
                for _ in range(30):
                    time.sleep(1)                
                self.main_loop()
        except:
            self.clean_up()
            raise
def main():

    prewarning_counter = 0
    warning_counter = 0
    alert_counter = 0

    print "[+] Starting bot..."

    # Read the config file
    print "[+] Reading config file..."
    config = ConfigParser.ConfigParser()
    config.read([os.path.expanduser("./config")])

    # Read data
    bot_name = config.get("bot", "name")
    bot_token = config.get("bot", "token")
    user_id = config.get("user", "allowed")

    # Last mssg id:
    last_id = int(load_last_id())
    print "[+] Last id: %d" % last_id

    # Configure regex
    regex = re.compile("[%s]" % re.escape(string.punctuation))

    # Create bot
    print "[+] Conectando tu bot..."
    bot = TelegramBot(bot_token)
    bot.update_bot_info().wait()

    print "\tBot conectado! El nombre de tu bot es: %s" % bot.username

    # Connect to hardware
    interface = SerialInterface()
    if platform.system() == "Windows":
        interface.connect(config.get("system", "port_Windows"), 115200)
    if platform.system() == "Darwin":
        interface.connect(config.get("system", "port_Mac"), 115200)
    else:
        interface.connect(config.get("system", "port_Ubuntu"), 115200)

    # Send special keyboard:
    send_keyboard(bot, user_id)

    print bot

    while True:
        try:
            updates = bot.get_updates(offset=last_id).wait()
            # print updates[0].message.sender
            # print "-------------------------------"

            for update in updates:

                id = update.message.message_id
                update_id = update.update_id
                user = update.message.sender

                chat_id = update.message.chat.id
                text = update.message.text

                if int(update_id) > last_id:
                    last_id = update_id
                    save_last_id(last_id)
                    save_log(id, update_id, chat_id, text)

                    # text = regex.sub('', text)
                    if text:
                        words = text.split()

                        for i, word in enumerate(words):
                            # Process commands:
                            if word == "/start":
                                print "New user started the app: " + str(user)
                                send_keyboard(bot, chat_id)
                            elif word == "/pollution":

                                # Acceso al html
                                d = pq(
                                    url="http://www.mambiente.munimadrid.es/opencms/opencms/calaire/consulta/Gases_y_particulas/informegaseshorarios.html?__locale=es"
                                )

                                # Selection of data date
                                date_data = d("span[class=tabla_titulo_fecha]")
                                date_data = date_data.text()
                                # print (date_data)

                                # Selection of station name
                                station_name = d('td[class="primertd"]')
                                station_name = station_name.append("**")
                                station_name = station_name.text()
                                station_name = station_name.split("**")
                                # print(station_name)

                                del station_name[0]  # Delete the first empty element of  the list

                                # Selection of all the N02 data
                                no2rawdata = d('td[headers="NO2"]')
                                no2data = no2rawdata.text()
                                no2data = no2data.replace("-", "0")  # Replaces no data with a 0
                                no2data = no2data.split(" ")
                                no2data = map(int, no2data)  # int conversion

                                # Info output
                                print ("Contaminacion de NO2 en Madrid-Fecha: " + date_data)
                                bot.send_message(chat_id, "\n\nContaminacion de NO2 en Madrid-Fecha: " + date_data)
                                t.sleep(3)

                                for x in range(len(no2data)):
                                    if no2data[x] > 400:
                                        print ("\n")
                                        print (
                                            station_name[x]
                                            + ": "
                                            + str(no2data[x])
                                            + " microgramos/metro cubico"
                                            + "-POSIBLE ALERTA POR POLUCION"
                                        )
                                        bot.send_message(
                                            chat_id,
                                            station_name[x]
                                            + ": "
                                            + str(no2data[x])
                                            + " microgramos/metro cubico"
                                            + "-POSIBLE ALERTA POR POLUCION",
                                        )
                                        alert_counter = alert_counter + 1
                                    elif no2data[x] > 250:
                                        print ("\n")
                                        print (
                                            station_name[x]
                                            + ": "
                                            + str(no2data[x])
                                            + " microgramos/metro cubico"
                                            + "-POSIBLE AVISO POR POLUCION"
                                        )
                                        bot.send_message(
                                            chat_id,
                                            station_name[x]
                                            + ": "
                                            + str(no2data[x])
                                            + " microgramos/metro cubico"
                                            + "-POSIBLE AVISO POR POLUCION",
                                        )
                                        warning_counter = warning_counter + 1
                                    elif no2data[x] > 200:
                                        print ("\n")
                                        print (
                                            station_name[x]
                                            + ": "
                                            + str(no2data[x])
                                            + " microgramos/metro cubico"
                                            + "-POSIBLE PREAVISO POR POLUCION"
                                        )
                                        bot.send_message(
                                            chat_id,
                                            station_name[x]
                                            + ": "
                                            + str(no2data[x])
                                            + " microgramos/metro cubico"
                                            + "-POSIBLE PREAVISO POR POLUCION",
                                        )
                                        prewarning_counter = prewarning_counter + 1
                                    else:
                                        print ("\n")
                                        print (station_name[x] + ": " + str(no2data[x]) + " microgramos/metro cubico")
                                        bot.send_message(
                                            chat_id,
                                            station_name[x] + ": " + str(no2data[x]) + " microgramos/metro cubico",
                                        )

                                        # Zowi pollution reaction
                                if alert_counter > 0:
                                    interface.gestureZowi("sad")
                                elif warning_counter > 0:
                                    interface.gestureZowi("angry")
                                elif prewarning_counter > 0:
                                    interface.gestureZowi("nervous")
                                else:
                                    interface.gestureZowi("superhappy")

                                    # interface.testZowi()
                                    # bot.send_message(chat_id, "Probando el bot!")
                                break

        except (KeyboardInterrupt, SystemExit):
            print "\nkeyboardinterrupt caught (again)"
            print "\n...Program Stopped Manually!"
            raise
Example #23
0
    # ('BackLeft', time_offset * 4),
]


def toDegreeInt(num):
    return int(num * 180 / math.pi)


def getStep(time):
    for s in coords[::-1]:
        if s[0] < time:
            return s
    return coords[-1]


inter = SerialInterface('/dev/tty.usbmodem1421', baud=115200)
inter.Listen()
time.sleep(1)

initial_time = time.time()
last_time = initial_time

while time.time() - initial_time < total_time:
    cur_time = time.time()
    if cur_time - last_time > interval:
        last_time = cur_time
        diff_ms = (cur_time - initial_time) * 1000

        for leg in legs:
            leg_time = (diff_ms * time_factor + leg[1]) % stride_duration
            step = getStep(leg_time)
Example #24
0
            fillcolor=stimulus['Color'])

        SoundStimuliList[stimulus_name].initLocalizedSound(
            center=stimulus['CenterPosition'],
            width=stimulus['Modulation']['Width'],
            trackLength=VirtualTrackLength,
            maxGain=stimulus['BaselineGain'],
            minGain=stimulus['Modulation']['CutoffGain'])
        SoundStimuliList[stimulus_name].change_gain(
            -90.0)  # start off turned off

    time.sleep(1.0)

from SerialInterface import SerialInterface

Interface = SerialInterface(SerialPort=args.serial_port)

if 'GPIO' in Config:
    for gpio_label, gpio_config in Config['GPIO'].items():
        Interface.add_gpio(gpio_label, gpio_config)

from RewardZone import ClassicalRewardZone, OperantRewardZone

RewardsList = []
for reward_name, reward in Config['RewardZones']['RewardZoneList'].items():
    if (reward['Type'] == 'Classical') | (reward['Type'] == 'Operant'):
        if reward['DispensePin'] not in Interface.GPIOs:
            raise ValueError('Dispense pin not in defined GPIO list')

        if reward['RewardSound'] != 'None':
            if reward['RewardSound'] not in Beeps:
Example #25
0
class Controller:
    def __init__(self, view=None):
        """
        :param view:AppFrame
        :return:Controller
        """

        self.view = view
        self.serial = SerialInterface(view=self.view)
        self.data = []
        self.initiatives = []
        self.members = []
        self.http = HttpInterface()
        self.conf = None

    def set_view(self, view):
        self.view = view
        self.serial.set_view(view)

    def get_interfaces(self):
        if not self.serial:
            return []
        else:
            return self.serial.get_available_serial_ports()

    def get_initiatives(self):
        return [i.get_name() for i in self.initiatives]

    def get_members(self):
        return [i.get_name() for i in self.members]

    def set_initiatives(self, inits):
        self.initiatives = inits

    def _view_message(self, s, level=1):
        if not self.view:
            raise RuntimeError("Controller does not have a view linked to it, cannot send it a message.")
        else:
            self.view.display_message(s, level)

    def upload(self, source):
        print "Controller.upload(source='" + source + "')"
        self._view_message("Attempting to gather data from the arduino")

        result = self.serial.connect(source)

        self._view_message("===========================")

        if not result:
            self._view_message("Failed to gather data from Arduino.", 2)
        else:
            self._view_message("Successfully gathered data from Arduino")
            self.data = result

        return result

    def reset(self):
        self.data = []
        self.serial.reset()

    def init(self):
        """
        Initializes the application logic:
        1) Checks that remote host for web server is available
        2) Fetches and stores current initiatives and tags from remote web server
        3) Other?
        :return: True if all checks and setup pass, False otherwise.
        """

        # Load the remote host info from the config file

        self.conf = cp.ConfigParser()
        self.conf.read('config.ini')
        self.http.set_host(str(self.conf.get('remotehost', 'hostname')))
        self.http.set_port(str(self.conf.get('remotehost', 'port')))

        print "http interface is configured to: " + str(self.http)

        # Check that the remote host can be connected to.

        if not self.http.check_remote():
            raise Exception("Could not contact server at: " + str(self.http.host) + " on port: " + str(self.http.port))

        # Fetch initiatives and tags from remote host

        self.initiatives = self.http.fetch_initiatives()
        self.members = self.http.fetch_members()

    def show_data(self):

        self.data = self.serial.get_data()

        if self.data:
            self._view_message("Data is: ")
            for i in self.data:
                self._view_message(str(i))

    def get_data(self):
        if self.data:
            return self.data
        else:
            self.data = self.serial.get_data()
            return self.data

    def get_tags_by_init(self, init_name):

        for i in self.initiatives:
            if i.get_name() == init_name:
                return i.get_tags()

    def find_init_by_name(self, name):

        for i in self.initiatives:
            if i.get_name() == name:
                return i

        return None

    def apply_init_to_data(self, init, data):

        tags = self.get_tags_by_init(init)

        print tags

        for d in self.data:
            d.initiative = self.find_init_by_name(init)
            d.tag = d.initiative.get_tags()[d.action-1]

        return self.data

    def get_member_from_name(self, name):
        for m in self.members:
            if m.name == name:
                return m

        return None

    def send_data(self, username):
        self.apply_init_to_data(self.view.initiatives.GetValue(), self.data)

        member = self.get_member_from_name(self.view.members.GetValue())

        print member

        for d in self.data:
            self.http.send_data(member.get_id(), d.initiative.get_id(), d.tag.get_id(),d.getUTCSeconds(), username)
Example #26
0
def main():
    print '[+] Starting bot...'

    # Read the config file
    print '[+] Reading config file...'
    config = ConfigParser.ConfigParser()
    config.read([os.path.expanduser('./config')])

    # Read data
    bot_name = config.get('bot', 'name')
    bot_token = config.get('bot', 'token')
    user_id = config.get('user', 'allowed')

    # Last mssg id:
    last_id = int(load_last_id())
    print '[+] Last id: %d' % last_id

    # Configure regex
    regex = re.compile('[%s]' % re.escape(string.punctuation))

    # Create bot
    print '[+] Connecting bot...'
    bot = TelegramBot(bot_token)
    bot.update_bot_info().wait()

    print '\tBot connected! Bot name: %s' % bot.username

    # Connect to hardware
    interface = SerialInterface()
    if platform.system() == 'Windows' :
        interface.connect('COM3', 19200)
    else:
        interface.connect('/dev/ttyUSB0', 19200)

    # Send special keyboard:
    send_keyboard(bot, user_id)

    print bot

    while True:
        try:
            updates = bot.get_updates(offset=last_id).wait()
            #print updates[0].message.sender
            #print updates[0].message.message_id
            #print "-------------------------------"

            itera = 0
            for update in updates:

                #print len(update.message)
                if update.message is not None:

                    #print update.message.text
                    #print "*************************** iteration: "

                    id = update.message.message_id
                    update_id = update.update_id
                    user = update.message.sender

                    chat_id = update.message.chat.id
                    text = update.message.text

                    if int(update_id) > last_id:
                        last_id = update_id
                        save_last_id(last_id)
                        save_log(id, update_id, chat_id, text)

                        #text = regex.sub('', text)
                        if text:
                            words = text.split()

                            for i, word in enumerate(words):

                                print word

                                # Process commands:
                                if word == '/start':
                                    print "New user started the app: " + str(user)
                                    send_keyboard(bot, chat_id)
                                elif word == '/flag':
                                    if update.message.sender.username  == 'paclema' : interface.sendFlagWave(1)
                                    bot.send_message(chat_id, "Moviendo la bandera " + get_user_name(update.message.sender) + "!")
                                elif word == '/rainbow':
                                    interface.sendRainbow()
                                    break
                                elif word == '/foto':
                                    #interface.sendFlagWave(1)
                                    interface.sendStripColor(0,0,0)
                                    for a in range(30):
                                        interface.sendStripBarColor(0, 2*a, 8.5*a, 0, 0)
                                        t.sleep(0.03)

                                    interface.sendStripColor(0,0,0)
                                    t.sleep(0.2)
                                    interface.sendStripColor(0,0,0)
                                    cam.start()
                                    bot.send_message(chat_id, get_user_name(update.message.sender) + " quiere una foto!")

                                    if platform.system() == 'Windows' :
                                        img = pygame.Surface((640,480))
                                        cam.get_image(img)
                                    else:
                                        img = cam.get_image()

                                    pygame.image.save(img,"./snap_photo.jpg")
                                    pygame.mixer.music.load("./camera_shutter.mp3")
                                    interface.sendStripColor(255,255,255)
                                    pygame.mixer.music.play()

                                    fp = open('snap_photo.jpg', 'rb')
                                    file_info = InputFileInfo('snap_photo.jpg', fp, 'image/jpg')

                                    f = InputFile('photo', file_info)

                                    bot.send_photo(chat_id, photo=f)

                                    cam.stop()
                                    print "[" + t.strftime("%c") + "]" + " Foto enviada de " + get_user_name(update.message.sender, True, True) + "!"
                                    t.sleep(0.3)
                                    interface.sendStripColor(0,0,0)

                                    break
                                else:
                                    bot.send_message(chat_id, "Bad syntax!")
                                    break

                                # Restricted API
                                if int(user_id) == user.id:
                                    if word == '/move':
                                        try:
                                            interface.sendMove(int(words[i+1]))
                                            break
                                        except Exception, e:
                                            print e


        except (KeyboardInterrupt, SystemExit):
            print '\nkeyboardinterrupt caught (again)'
            print '\n...Program Stopped Manually!'
            raise
Example #27
0

def factory():
    def settings_factory():
        return [0, 0]

    settings_dict = defaultdict(settings_factory)
    distances_dict = defaultdict(list)
    return (settings_dict, distances_dict)


history_dict = defaultdict(factory)

rr = RoboRealmInterface()
rr.connect()
serial_port = SerialInterface()
if not serial_port.open("COM16"):
    print('Error opening serial port %s' % "COM16")


def rr_monitor():
    HISTORY_LENGTH = 300

    while rr_lock.locked():
        with pose_dat_lock:
            for k, v in rr.get_robot_positions().items():
                pose_dat[k].append(v)
                if (len(pose_dat[k]) > HISTORY_LENGTH):
                    pose_dat[k].popleft()
            for robot_id in pose_dat.keys():
                print('\t{0}: {1}'.format(robot_id, pose_dat[robot_id][-1]))