# data[].attributes.attachment_link.readable_text
import network # for wifi connexion

class connexion:
    wlan = network.WLAN(network.STA_IF)
    def __init__(self):
        self.wlan.active(True)
       
     #connexion wifi
    def connect_wifi(self,WIFI_SSID,WIFI_PASSWORD):
        if not self.wlan.isconnected():
            print("Connexion au WiFi en cours...")
            self.wlan.connect(WIFI_SSID, WIFI_PASSWORD)
            while not self.wlan.isconnected():
                pass
        print("Connect�� au r��seau WiFi")
    def getIP(self):
        if self.wlan.isconnected():
            return self.wlan.ifconfig()[0]
        else:
            return ''
    def disconnect_wifi(self):
        if not self.wlan.isconnected():
            print('Carte d��j�� d��connect��e')
        else:
            self.wlan.disconnect()
            print('carte d��connect��e avec succ��s')
        pass
        
     

# data[].attributes.attachment_link.readable_text
from requests import * 
class MyCloud:
    url ='http://things.ubidots.com/api/v1.6/devices/'
    headers={'X-Auth-Token':"" ,'Content-Type':'application/json'}
    def __init__(self, obj,token):
        self.url =self.url+obj
        self.headers={'X-Auth-Token':token ,'Content-Type':'application/json'}
    def post(self,data):
        try:
            req=post(url=self.url,headers=self.headers,json=data)
            print(data," Envoy��e avec succ��s")
        except Exception as e:
            print("Erreur lors de l'envoi :", e)
            
        #print(req.text)
    def get(self,variable):
        url2 = self.url+'/'+variable+'/lv'
        req=get(url=url2,headers=self.headers)
        val =float(req.text)
        return int(val)

# data[].attributes.attachment_link.readable_text
import machine
import time

# Thanks to:
# https://youtu.be/B86nqDRskVU


class Motor:
    stepms = 10

    # Do be defined by subclasses
    maxpos = 0
    states = []

    def __init__(self, p1, p2, p3, p4, stepms=None):
        self.pins = [p1, p2, p3, p4]

        if stepms is not None:
            self.stepms = stepms

        self._state = 0
        self._pos = 0

    def __repr__(self):
        return '<{} @ {}>'.format(
            self.__class__.__name__,
            self.pos,
        )

    @property
    def pos(self):
        return self._pos

    @classmethod
    def frompins(cls, *pins, **kwargs):
        return cls(*[machine.Pin(pin, machine.Pin.OUT) for pin in pins],
                   **kwargs)

    def zero(self):
        self._pos = 0

    def _step(self, dir):
        state = self.states[self._state]

        for i, val in enumerate(state):
            self.pins[i].value(val)

        self._state = (self._state + dir) % len(self.states)
        self._pos = (self._pos + dir) % self.maxpos

    def step(self, steps):
        dir = 1 if steps >= 0 else -1
        steps = abs(steps)

        for _ in range(steps):
            t_start = time.ticks_ms()

            self._step(dir)

            t_end = time.ticks_ms()
            t_delta = time.ticks_diff(t_end, t_start)
            time.sleep_ms(self.stepms - t_delta)

    def step_until(self, target, dir=None):
        if target < 0 or target > self.maxpos:
            raise ValueError(target)

        if dir is None:
            dir = 1 if target > self._pos else -1
            if abs(target - self._pos) > self.maxpos/2:
                dir = -dir

        while True:
            if self._pos == target:
                break
            self.step(dir)

    def step_until_angle(self, angle, dir=None):
        if angle < 0 or angle > 360:
            raise ValueError(angle)

        target = int(angle / 360 * self.maxpos)
        self.step_until(target, dir=dir)


class FullStepMotor(Motor):
    stepms = 5
    maxpos = 2048
    states = [
        [1, 1, 0, 0],
        [0, 1, 1, 0],
        [0, 0, 1, 1],
        [1, 0, 0, 1],
    ]


class HalfStepMotor(Motor):
    stepms = 3
    maxpos = 4096
    states = [
        [1, 0, 0, 0],
        [1, 1, 0, 0],
        [0, 1, 0, 0],
        [0, 1, 1, 0],
        [0, 0, 1, 0],
        [0, 0, 1, 1],
        [0, 0, 0, 1],
        [1, 0, 0, 1],
    ]