|
| 1 | +#!/usr/bin/env python3 |
| 2 | + |
| 3 | +import os |
| 4 | +import robomodules as rm |
| 5 | +import serial |
| 6 | +from messages import * |
| 7 | + |
| 8 | +ADDRESS = os.environ.get("BIND_ADDRESS","localhost") |
| 9 | +PORT = os.environ.get("BIND_PORT", 11297) |
| 10 | + |
| 11 | +FREQUENCY = 10 |
| 12 | + |
| 13 | +class ArduinoCommsModule(rm.ProtoModule): |
| 14 | + def __init__(self, addr, port): |
| 15 | + self.subscriptions = [MsgType.CTRL_MSG] |
| 16 | + super().__init__(addr, port, message_buffers, MsgType, FREQUENCY, self.subscriptions) |
| 17 | + try: |
| 18 | + self.serialConnection = serial.Serial('/dev/ttyUSB0', 9600) |
| 19 | + except Exception: |
| 20 | + raise RuntimeError("serial connection to Arduino failed") |
| 21 | + |
| 22 | + def msg_received(self, msg, msg_type): |
| 23 | + # This gets called whenever any message is received |
| 24 | + if msg_type == MsgType.CTRL_MSG: |
| 25 | + # turn it into a string |
| 26 | + # turn the string into binary |
| 27 | + # send the binary |
| 28 | + self.serialConnection.write(self._stringToBinary(self._messageToString(msg))) |
| 29 | + |
| 30 | + def tick(self): |
| 31 | + # this function will get called in a loop with FREQUENCY frequency |
| 32 | + # from https://www.raspberrypi.org/forums/viewtopic.php?f=32&t=54182 |
| 33 | + msg = self._stringToMessage(self._binaryToString(self.serialConnection.readline())) |
| 34 | + if msg: |
| 35 | + self.write(msg, MsgType.ORIENTATION_MSG) |
| 36 | + |
| 37 | + def _messageToString(self, m): |
| 38 | + ans = "$" |
| 39 | + # go through each of the properties in the message |
| 40 | + for prop in ["x", "y", "z", "roll", "pitch", "yaw"]: |
| 41 | + # convert the number into a string |
| 42 | + # separate the properties with a semicolon |
| 43 | + ans += (str(getattr(m, prop)) + ";") |
| 44 | + return ans |
| 45 | + |
| 46 | + def _stringToBinary(self, s): |
| 47 | + return bytes(s, "ascii") |
| 48 | + |
| 49 | + def _binaryToString(self, b): |
| 50 | + return b.decode('ascii') |
| 51 | + |
| 52 | + def _stringToMessage(self, s): |
| 53 | + ans = OrientationMsg() |
| 54 | + # take off leading '$' |
| 55 | + s = s[1:] if s[0] == "$" |
| 56 | + # get all of the values in the string |
| 57 | + # need to take off the last empty string that split will leave |
| 58 | + numbers = (s.split(";"))[0:-1] |
| 59 | + # didn't get a good input |
| 60 | + if len(numbers) != 3: |
| 61 | + return None |
| 62 | + # assumes the values are coming in in that order |
| 63 | + for (number, name) in zip(numbers, ["roll", "pitch", "yaw"]): |
| 64 | + setattr(ans, name, number) |
| 65 | + |
| 66 | + return ans |
| 67 | + |
| 68 | + |
| 69 | +def main(): |
| 70 | + module = ArduinoCommsModule(ADDRESS, PORT) |
| 71 | + module.run() |
| 72 | + |
| 73 | +if __name__ == "__main__": |
| 74 | + main() |
0 commit comments