Exemplo n.º 1
0
def date_obj(d=None):
    if d is None:
        d = arrow.now()
    else:
        d = arrow.get(d)

    return json_obj(type='mention',
                    mention=json_obj(type='date',
                                     date=json_obj(start=d.isoformat()),
                                     end=None))
Exemplo n.º 2
0
async def _triage(sa, channel):
    t = json_obj(U.Pickle().read('err_dict'))
    header, *msgs = _iter_triage(t)
    await sa.post_message(channel, blocks=header)
    for msg in msgs:
        await sa.post_message(channel, blocks=DividerBlock())
        if msg:
            await sa.post_message(channel, text=msg)
Exemplo n.º 3
0
 async def record(self,
                  filename: str,
                  how_long_secs: Optional[float] = None,
                  blocking=False):
     """record audio"""
     fn = f'{filename.rstrip(".wav")}.wav'
     res = await self._post('audio/record/start', json_obj(FileName=fn))
     await self._handle_blocking_record_call(how_long_secs, blocking)
     return res
Exemplo n.º 4
0
 def to_json(self, debounce_ms) -> json_obj:
     payload = json_obj(Operation='subscribe',
                        Type=self.sub.sub_type.value,
                        DebounceMS=debounce_ms,
                        EventName=self.event_name)
     if self.sub.ec:
         payload.EventConditions = [ec.json for ec in self.sub.ec]
     if self.sub.return_prop:
         payload.ReturnProperty = self.sub.return_prop
     return payload
Exemplo n.º 5
0
 def json(self) -> Dict[str, float]:
     names = [
         name for name in 'pitch roll yaw'.split()
         if getattr(self, name) is not None
     ]
     if not names:
         return {}
     return json_obj(Velocity=self.velocity,
                     Units='degrees',
                     **self._get_denormalized(self, names))
Exemplo n.º 6
0
 async def list(self, pretty=False) -> Dict[str, json_obj]:
     """
     get images available on device as dict(name=json)
     store in `self.saved_images`
     return dict
     """
     images = await self._get_j('images/list')
     res = self.saved_images = json_obj((i.name, i) for i in images)
     if pretty:
         print_pretty(res)
     return res
Exemplo n.º 7
0
 async def list(self, pretty=False) -> Dict[str, json_obj]:
     """
     get audio metadata available on device as dict(name=json)
     store in `self.saved_audio`
     return dict
     """
     audio = await self._get_j('audio/list')
     res = self.saved_audio = json_obj((a.name, a) for a in audio)
     if pretty:
         print_pretty(res)
     return res
Exemplo n.º 8
0
 async def drive_arc(self,
                     heading_degrees: float,
                     radius_m: float,
                     time_ms: float,
                     *,
                     reverse: bool = False):
     payload = json_obj(Heading=heading_degrees * -1,
                        Radius=radius_m,
                        TimeMs=time_ms,
                        Reverse=reverse)
     return await self._post('drive/arc', payload)
Exemplo n.º 9
0
def _parse_args(s: str) -> Tuple[str, json_obj, List[str]]:
    str_res = []
    flag_res = []
    arg_res = json_obj()
    for w in s.split():
        if w.startswith('--'):
            if '=' in w:
                split = w.index('=')
                arg_res[w[2:split]] = w[split + 1:]
            else:
                flag_res.append(w[2:])

        else:
            str_res.append(w)

    return ' '.join(str_res), arg_res, flag_res
Exemplo n.º 10
0
async def calibrate_misty():
    """move misty's actuators to extreme positions and record the values"""
    from misty_py.api import MistyAPI
    api = MistyAPI()
    res = {}
    await api.movement.move_head(0, 0, 0, 50)
    await api.movement.move_arms(-50, -50, 50, 50)
    await asyncio.sleep(2)

    async def _head(*_args, **_kwargs):
        await api.movement.move_head(*_args, **_kwargs)
        await asyncio.sleep(3)
        return (await api.movement.get_actuator_values(normalize=False))[a]

    for a in Actuator.pitch, Actuator.roll, Actuator.yaw:
        kwargs = {a.name: 110, 'velocity': 60}
        pos = await _head(**kwargs)

        kwargs = {a.name: -110, 'velocity': 60}
        neg = await _head(**kwargs)

        zero = await _head(0, 0, 0, 50)
        res[a] = PosZeroNeg(pos, zero, neg)

    async def _arms(**_kwargs):
        await api.movement.move_arms(**_kwargs)
        await asyncio.sleep(2)
        positions = await api.movement.get_actuator_values(normalize=False)
        return positions[Actuator.left_arm], positions[Actuator.right_arm]

    l_pos, r_pos = await _arms(l_position=110, r_position=110, l_velocity=80, r_velocity=80)
    l_neg, r_neg = await _arms(l_position=-110, r_position=-110, l_velocity=80, r_velocity=80)
    l_0, r_0 = await _arms(l_position=0, r_position=0, l_velocity=50, r_velocity=50)

    res[Actuator.left_arm] = PosZeroNeg(l_pos, l_0, l_neg)
    res[Actuator.right_arm] = PosZeroNeg(r_pos, r_0, r_neg)

    print()
    print(json_obj((k.name, v) for k, v in res.items()).pretty)
    return res
Exemplo n.º 11
0
 async def connect_wifi(self, ssid):
     """connect to known wifi"""
     return await self._post('networks', json_obj(NetworkId=ssid))
Exemplo n.º 12
0
 def __init__(self, block):
     self._block = json_obj(block)
     self._children = []
Exemplo n.º 13
0
 async def reboot(self, core=True, sensory_services=True):
     return await self._post('reboot', json_obj(Core=core, SensoryServices=sensory_services))
Exemplo n.º 14
0
 def __init__(self, api):
     super().__init__(api)
     self.saved_audio = json_obj()
Exemplo n.º 15
0
 def json(self) -> json_obj:
     return json_obj(Property=self.name,
                     Inequality=self.inequality,
                     Value=self.value)
Exemplo n.º 16
0
def _flatten_form(form) -> json_obj:
    """transform {k: [v]} -> {k: v}"""
    return json_obj((k, first(v) if isinstance(v, list) and len(v) == 1 else v)
                    for k, v in form.items())
Exemplo n.º 17
0
async def stream(websocket, path, sleep_time=1.0):
    print(type(websocket), websocket, type(path), path)
    while True:
        j = json_obj(Type=Sub.random())
        await websocket.send(j.json_str)
        await asyncio.sleep(sleep_time)
Exemplo n.º 18
0
 async def remove_blink_mappings(self, image: str, *images: str):
     return await self._delete('blink/images',
                               json_obj(BlinkImages=(image, ) + images))
Exemplo n.º 19
0
 def __init__(self, api):
     super().__init__(api)
     self.saved_images = json_obj()
Exemplo n.º 20
0
def parse_config(conf=SLACK_CONF):
    res = json_obj()
    with open(conf) as f:
        exec(f.read(), res, res)
    del res['__builtins__']
    return res
Exemplo n.º 21
0
 async def set_log_level(self, log_level: str):
     return await self._post('logs/level', json_obj(LogLevel=log_level))
Exemplo n.º 22
0
 async def forget_wifi(self, ssid):
     return await self._delete('networks', json_obj(NetworkId=ssid))
Exemplo n.º 23
0
SelfState = json_obj(
    **{
        "eventName": "SelfState",
        "message": {
            "acceleration": None,
            "batteryChargePercent": 0,
            "batteryVoltage": 0,
            "bumpedState": {
                "disengagedSensorIds": [],
                "disengagedSensorNames": [],
                "disengagedSensors": [],
                "engagedSensorIds": [],
                "engagedSensorNames": [],
                "engagedSensors": []
            },
            "currentGoal": {
                "animation": None,
                "animationId": None,
                "directedMotion": None,
                "directedMotionBehavior": "SupersedeAll",
                "haltActionSequence": False,
                "haltAnimation": False
            },
            "isCharging": False,
            "localIPAddress": "10.0.1.160",
            "location": {
                "bearing": 2.1161846957231862,
                "bearingThreshold": {
                    "lowerBound": 0,
                    "upperBound": 0
                },
                "distance": 0.049783250606253104,
                "distanceThreshold": {
                    "lowerBound": 0,
                    "upperBound": 0
                },
                "elevation": -0.009038750542528028,
                "elevationThreshold": {
                    "lowerBound": 0,
                    "upperBound": 0
                },
                "pose": {
                    "bearing": 2.1161846957231862,
                    "created": "2018-09-17T21:01:35.7312016Z",
                    "distance": 0.049783250606253104,
                    "elevation": -0.009038750542528028,
                    "frameId": "WorldOrigin",
                    "framesProvider": {
                        "rootFrame": {
                            "created": "2018-09-17T18:21:22.8435331Z",
                            "id": "RobotBaseCenter",
                            "isStatic": True,
                            "linkFromParent": {
                                "isStatic": True,
                                "parentFrameId": "",
                                "transformFromParent": {
                                    "bearing": 0,
                                    "distance": 0,
                                    "elevation": 0,
                                    "pitch": 0,
                                    "quaternion": {
                                        "isIdentity": True,
                                        "w": 1,
                                        "x": 0,
                                        "y": 0,
                                        "z": 0
                                    },
                                    "roll": 0,
                                    "x": 0,
                                    "y": 0,
                                    "yaw": 0,
                                    "z": 0
                                },
                                "transformToParent": {
                                    "bearing": 3.141592653589793,
                                    "distance": 0,
                                    "elevation": 0,
                                    "pitch": 0,
                                    "quaternion": {
                                        "isIdentity": True,
                                        "w": 1,
                                        "x": 0,
                                        "y": 0,
                                        "z": 0
                                    },
                                    "roll": 0,
                                    "x": 0,
                                    "y": 0,
                                    "yaw": 0,
                                    "z": 0
                                }
                            }
                        }
                    },
                    "homogeneousCoordinates": {
                        "bearing": 2.1161846957231862,
                        "distance": 0.049783250606253104,
                        "elevation": -0.009038750542528028,
                        "pitch": -0.18708743155002594,
                        "quaternion": {
                            "isIdentity": False,
                            "w": 0.99558717,
                            "x": -0.008987884,
                            "y": -0.09339719,
                            "z": -0.0015491969
                        },
                        "roll": -0.017920719552386073,
                        "x": -0.025824014097452164,
                        "y": 0.04255925118923187,
                        "yaw": -0.001430802591800146,
                        "z": 0.00044997225631959736
                    },
                    "pitch": -0.18708743155002594,
                    "roll": -0.017920719552386073,
                    "x": -0.025824014097452164,
                    "y": 0.04255925118923187,
                    "yaw": -0.001430802591800146,
                    "z": 0.00044997225631959736
                },
                "unitOfMeasure": "None"
            },
            "mentalState": {
                "affect": {
                    "arousal": 0,
                    "dominance": 0,
                    "valence": 0
                },
                "created": "2018-09-17T21:01:35.7312016Z",
                "personality": {
                    "agreeableness": 0,
                    "conscientiousness": 0,
                    "extraversion": 0,
                    "neuroticism": 0,
                    "openness": 0
                },
                "physiologicalBehavior": {
                    "hunger": {
                        "isEating": False,
                        "level": 0
                    },
                    "sleepiness": {
                        "isSleeping": False,
                        "level": 0
                    }
                }
            },
            "occupancyGridCell": {
                "x": 0,
                "y": 0
            },
            "occupancyGridCellMeters": 0,
            "orientation": {
                "pitch": -0.18708743155002594,
                "roll": -0.017920719552386073,
                "yaw": -0.001430802591800146
            },
            "position": {
                "x": -0.025824014097452164,
                "y": 0.04255925118923187,
                "z": -0.025824014097452164
            },
            "slamStatus": {
                "runMode": "Exploring",
                "sensorStatus": "Ready",
                "status": 132
            },
            "stringMessages": None,
            "touchedState": {
                "disengagedSensors": [],
                "engagedSensors": []
            }
        },
        "type": "SelfState"
    })
Exemplo n.º 24
0
import asyncio

import arrow
import uvloop

from misty_py.api import MistyAPI
from misty_py.misty_ws import MistyWS
from misty_py.subscriptions import Sub, SubReq, SubData
from misty_py.utils import json_obj, RGB, HeadSettings

# print(json_obj(dict(a=4)))
# t = json_obj([dict(a=4, b=[dict(ab=84, hm=53)]), dict(b=5, c=67)])
t = json_obj(
    [dict(a=4, b=[8, 7, [12, dict(ahoe=234)]]),
     dict(b=5, c=67, e=dict(a=5))])
t = json_obj()

x = t.tuse = 4
print(x)
# t = json_obj(dict(a=dict(b=4)))
t = t
print(t)
# print(json_obj())
# print(json_obj(dict(a=5), b=6))
# print(json_obj([4, 5]))

print(HeadSettings(yaw=40).json)
sys.exit

api = MistyAPI('localhost:9999')
Exemplo n.º 25
0
 async def get_logs(self, date: arrow.Arrow = arrow.now()) -> str:
     params = json_obj()
     if date:
         params.date = date.format('YYYY/MM/DD')
     return (await self._get('logs', **params)).json()['result']
Exemplo n.º 26
0
 def _get_denormalized(obj, names: List[str]):
     actuators = [Actuator[n] for n in names]
     aps = _get_calibrated_actuator_positions()
     return json_obj((a.name.capitalize(), aps[a].denormalize(getattr(obj, a.name))) for a in actuators)
Exemplo n.º 27
0
 async def get_websocket_names(self, class_name: Optional[str] = None):
     """specs for websocket api"""
     params = json_obj()
     if class_name:
         params.websocketClass = class_name
     return await self._get_j('websockets', **params)
Exemplo n.º 28
0
 async def set_blinking(self, on=True):
     return await self._post('blink', json_obj(Blink=on))