Test Temperature

 

Raspberry con Wii fit

Proyecto para leer peso de Wii fit y enviar a mqdt, código python 2.7:

  1.  
  2. #!/usr/bin/env python
  3.  
  4. #for wii balance board
  5. import collections
  6. import time
  7. import bluetooth
  8. import sys
  9. import subprocess
  10.  
  11. #for mqtt
  12. import sys                                 
  13. import ssl
  14. import json
  15. import time
  16. import paho.mqtt.client as mqtt
  17.  
  18. #---------- mqtt init -------------
  19. def on_publish(mosq, obj, mid):
  20.     print("published")
  21.  
  22. def on_connect(mqttc, obj, flags, rc):
  23.     if rc==0:
  24.         print ("Connection successful")
  25.     elif rc==1:
  26.         print ("Connection refused")
  27.     return
  28.  
  29. def on_disconnect(client, userdata, rc):
  30.     print("disonnected")
  31.  
  32. mqttc = mqtt.Client(client_id="RaspberryPi")
  33.  
  34.  
  35. mqttc.on_publish = on_publish
  36. mqttc.on_connect = on_connect
  37. mqttc.on_disconnect = on_disconnect
  38.  
  39.  
  40. mqttc.will_set("/wii-fit/peso",'{}',True)
  41.  
  42.  
  43.  
  44. mqttc.connect("test.mosquitto.org",1883)
  45. mqttc.loop_start()
  46. #----------------------------------
  47.  
  48. # --------- User Settings ---------
  49. WEIGHT_SAMPLES = 500
  50. # ---------------------------------
  51.  
  52. # Wiiboard Parameters
  53. CONTINUOUS_REPORTING = "04"  # Easier as string with leading zero
  54. COMMAND_LIGHT = 11
  55. COMMAND_REPORTING = 12
  56. COMMAND_REQUEST_STATUS = 15
  57. COMMAND_REGISTER = 16
  58. COMMAND_READ_REGISTER = 17
  59. INPUT_STATUS = 20
  60. INPUT_READ_DATA = 21
  61. EXTENSION_8BYTES = 32
  62. BUTTON_DOWN_MASK = 8
  63. TOP_RIGHT = 0
  64. BOTTOM_RIGHT = 1
  65. TOP_LEFT = 2
  66. BOTTOM_LEFT = 3
  67. BLUETOOTH_NAME = "Nintendo RVL-WBC-01"
  68.  
  69.  
  70. class EventProcessor:
  71.     def __init__(self):
  72.         self._measured = False
  73.         self.done = False
  74.         self._measureCnt = 0
  75.         self._events = range(WEIGHT_SAMPLES)
  76.  
  77.     def mass(self, event):
  78.         if (event.totalWeight > 2):
  79.             self._events[self._measureCnt] = event.totalWeight*2.20462
  80.             self._measureCnt += 1
  81.             if self._measureCnt == WEIGHT_SAMPLES:
  82.                 self._sum = 0
  83.                 for x in range(0, WEIGHT_SAMPLES-1):
  84.                     self._sum += event.totalWeight*2.20462
  85.                 self._weight = self._sum/WEIGHT_SAMPLES
  86.                 self._measureCnt = 0
  87.                 print str(self._weight * 0.453592) + " lbs"
  88.                 #publish ----------------------------------------------
  89.                 jsonstr = '{"DeviceId":0,"Readings":{"label":"Weight","data":' + str(self._weight) + '}}'
  90.                 jsonReading = json.loads(jsonstr)
  91.                 payloadJson = {}
  92.                 payloadJson['state'] = {}
  93.                 payloadJson['state']['desired'] = jsonReading
  94.                 mqttc.publish("/wii-fit/peso", str(self._weight * 0.453592) , qos = 1)
  95.                 #------------------------------------------------------
  96.             if not self._measured:
  97.                 self._measured = True
  98.  
  99.     @property
  100.     def weight(self):
  101.         if not self._events:
  102.             return 0
  103.         histogram = collections.Counter(round(num, 1) for num in self._events)
  104.         return histogram.most_common(1)[0][0]
  105.  
  106.  
  107. class BoardEvent:
  108.     def __init__(self, topLeft, topRight, bottomLeft, bottomRight, buttonPressed, buttonReleased):
  109.  
  110.         self.topLeft = topLeft
  111.         self.topRight = topRight
  112.         self.bottomLeft = bottomLeft
  113.         self.bottomRight = bottomRight
  114.         self.buttonPressed = buttonPressed
  115.         self.buttonReleased = buttonReleased
  116.         #convenience value
  117.         self.totalWeight = topLeft + topRight + bottomLeft + bottomRight
  118.  
  119. class Wiiboard:
  120.     def __init__(self, processor):
  121.         # Sockets and status
  122.         self.receivesocket = None
  123.         self.controlsocket = None
  124.  
  125.         self.processor = processor
  126.         self.calibration = []
  127.         self.calibrationRequested = False
  128.         self.LED = False
  129.         self.address = None
  130.         self.buttonDown = False
  131.         for i in xrange(3):
  132.             self.calibration.append([])
  133.             for j in xrange(4):
  134.                 self.calibration[i].append(10000)  # high dummy value so events with it don't register
  135.  
  136.         self.status = "Disconnected"
  137.         self.lastEvent = BoardEvent(0, 0, 0, 0, False, False)
  138.  
  139.         try:
  140.             self.receivesocket = bluetooth.BluetoothSocket(bluetooth.L2CAP)
  141.             self.controlsocket = bluetooth.BluetoothSocket(bluetooth.L2CAP)
  142.         except ValueError:
  143.             raise Exception("Error: Bluetooth not found")
  144.  
  145.     def isConnected(self):
  146.         return self.status == "Connected"
  147.  
  148.     # Connect to the Wiiboard at bluetooth address <address>
  149.     def connect(self, address):
  150.         if address is None:
  151.             print "Non existant address"
  152.             return
  153.         self.receivesocket.connect((address, 0x13))
  154.         self.controlsocket.connect((address, 0x11))
  155.         if self.receivesocket and self.controlsocket:
  156.             print "Connected to Wiiboard at address " + address
  157.             self.status = "Connected"
  158.             self.address = address
  159.             self.calibrate()
  160.             useExt = ["00", COMMAND_REGISTER, "04", "A4", "00", "40", "00"]
  161.             self.send(useExt)
  162.             self.setReportingType()
  163.             print "Wiiboard connected"
  164.         else:
  165.             print "Could not connect to Wiiboard at address " + address
  166.  
  167.     def receive(self):
  168.         while self.status == "Connected" and not self.processor.done:
  169.             data = self.receivesocket.recv(25)
  170.             intype = int(data.encode("hex")[2:4])
  171.             if intype == INPUT_STATUS:
  172.                 # TODO: Status input received. It just tells us battery life really
  173.                 self.setReportingType()
  174.             elif intype == INPUT_READ_DATA:
  175.                 if self.calibrationRequested:
  176.                     packetLength = (int(str(data[4]).encode("hex"), 16) / 16 + 1)
  177.                     self.parseCalibrationResponse(data[7:(7 + packetLength)])
  178.  
  179.                     if packetLength < 16:
  180.                         self.calibrationRequested = False
  181.             elif intype == EXTENSION_8BYTES:
  182.                 self.processor.mass(self.createBoardEvent(data[2:12]))
  183.             else:
  184.                 print "ACK to data write received"
  185.  
  186.     def disconnect(self):
  187.         if self.status == "Connected":
  188.             self.status = "Disconnecting"
  189.             while self.status == "Disconnecting":
  190.                 self.wait(100)
  191.         try:
  192.             self.receivesocket.close()
  193.         except:
  194.             pass
  195.         try:
  196.             self.controlsocket.close()
  197.         except:
  198.             pass
  199.         print "WiiBoard disconnected"
  200.  
  201.     # Try to discover a Wiiboard
  202.     def discover(self):
  203.         print "Press the red sync button on the board now"
  204.         address = None
  205.         bluetoothdevices = bluetooth.discover_devices(duration=6, lookup_names=True)
  206.         for bluetoothdevice in bluetoothdevices:
  207.             if bluetoothdevice[1] == BLUETOOTH_NAME:
  208.                 address = bluetoothdevice[0]
  209.                 print "Found Wiiboard at address " + address
  210.         if address is None:
  211.             print "No Wiiboards discovered."
  212.         return address
  213.  
  214.     def createBoardEvent(self, bytes):
  215.         buttonBytes = bytes[0:2]
  216.         bytes = bytes[2:12]
  217.         buttonPressed = False
  218.         buttonReleased = False
  219.  
  220.         state = (int(buttonBytes[0].encode("hex"), 16) << 8) | int(buttonBytes[1].encode("hex"), 16)
  221.         if state == BUTTON_DOWN_MASK:
  222.             buttonPressed = True
  223.             if not self.buttonDown:
  224.                 print "Button pressed"
  225.                 self.buttonDown = True
  226.  
  227.         if not buttonPressed:
  228.             if self.lastEvent.buttonPressed:
  229.                 buttonReleased = True
  230.                 self.buttonDown = False
  231.                 print "Button released"
  232.  
  233.         rawTR = (int(bytes[0].encode("hex"), 16) << 8) + int(bytes[1].encode("hex"), 16)
  234.         rawBR = (int(bytes[2].encode("hex"), 16) << 8) + int(bytes[3].encode("hex"), 16)
  235.         rawTL = (int(bytes[4].encode("hex"), 16) << 8) + int(bytes[5].encode("hex"), 16)
  236.         rawBL = (int(bytes[6].encode("hex"), 16) << 8) + int(bytes[7].encode("hex"), 16)
  237.  
  238.         topLeft = self.calcMass(rawTL, TOP_LEFT)
  239.         topRight = self.calcMass(rawTR, TOP_RIGHT)
  240.         bottomLeft = self.calcMass(rawBL, BOTTOM_LEFT)
  241.         bottomRight = self.calcMass(rawBR, BOTTOM_RIGHT)
  242.         boardEvent = BoardEvent(topLeft, topRight, bottomLeft, bottomRight, buttonPressed, buttonReleased)
  243.         return boardEvent
  244.  
  245.     def calcMass(self, raw, pos):
  246.         val = 0.0
  247.         #calibration[0] is calibration values for 0kg
  248.         #calibration[1] is calibration values for 17kg
  249.         #calibration[2] is calibration values for 34kg
  250.         if raw < self.calibration[0][pos]:
  251.             return val
  252.         elif raw < self.calibration[1][pos]:
  253.             val = 17 * ((raw - self.calibration[0][pos]) / float((self.calibration[1][pos] - self.calibration[0][pos])))
  254.         elif raw > self.calibration[1][pos]:
  255.             val = 17 + 17 * ((raw - self.calibration[1][pos]) / float((self.calibration[2][pos] - self.calibration[1][pos])))
  256.  
  257.         return val
  258.  
  259.     def getEvent(self):
  260.         return self.lastEvent
  261.  
  262.     def getLED(self):
  263.         return self.LED
  264.  
  265.     def parseCalibrationResponse(self, bytes):
  266.         index = 0
  267.         if len(bytes) == 16:
  268.             for i in xrange(2):
  269.                 for j in xrange(4):
  270.                     self.calibration[i][j] = (int(bytes[index].encode("hex"), 16) << 8) + int(bytes[index + 1].encode("hex"), 16)
  271.                     index += 2
  272.         elif len(bytes) < 16:
  273.             for i in xrange(4):
  274.                 self.calibration[2][i] = (int(bytes[index].encode("hex"), 16) << 8) + int(bytes[index + 1].encode("hex"), 16)
  275.                 index += 2
  276.  
  277.     # Send <data> to the Wiiboard
  278.     # <data> should be an array of strings, each string representing a single hex byte
  279.     def send(self, data):
  280.         if self.status != "Connected":
  281.             return
  282.         data[0] = "52"
  283.  
  284.         senddata = ""
  285.         for byte in data:
  286.             byte = str(byte)
  287.             senddata += byte.decode("hex")
  288.  
  289.         self.controlsocket.send(senddata)
  290.  
  291.     #Turns the power button LED on if light is True, off if False
  292.     #The board must be connected in order to set the light
  293.     def setLight(self, light):
  294.         if light:
  295.             val = "10"
  296.         else:
  297.             val = "00"
  298.  
  299.         message = ["00", COMMAND_LIGHT, val]
  300.         self.send(message)
  301.         self.LED = light
  302.  
  303.     def calibrate(self):
  304.         message = ["00", COMMAND_READ_REGISTER, "04", "A4", "00", "24", "00", "18"]
  305.         self.send(message)
  306.         self.calibrationRequested = True
  307.  
  308.     def setReportingType(self):
  309.         bytearr = ["00", COMMAND_REPORTING, CONTINUOUS_REPORTING, EXTENSION_8BYTES]
  310.         self.send(bytearr)
  311.  
  312.     def wait(self, millis):
  313.         time.sleep(millis / 1000.0)
  314.  
  315.  
  316. def main():
  317.     processor = EventProcessor()
  318.  
  319.     board = Wiiboard(processor)
  320.     if len(sys.argv) == 1:
  321.         print "Discovering board..."
  322.         address = board.discover()
  323.     else:
  324.         address = sys.argv[1]
  325.  
  326.     try:
  327.         # Disconnect already-connected devices.
  328.         # This is basically Linux black magic just to get the thing to work.
  329.         subprocess.check_output(["bluez-test-input", "disconnect", address], stderr=subprocess.STDOUT)
  330.         subprocess.check_output(["bluez-test-input", "disconnect", address], stderr=subprocess.STDOUT)
  331.     except:
  332.         pass
  333.  
  334.     print "Trying to connect..."
  335.     board.connect(address)  # The wii board must be in sync mode at this time
  336.     board.wait(200)
  337.     # Flash the LED so we know we can step on.
  338.     board.setLight(False)
  339.     board.wait(500)
  340.     board.setLight(True)
  341.     board.receive()
  342.  
  343. if __name__ == "__main__":
  344.     main()

Link original:
https://www.hackster.io/claude4/wii-balance-board-cloud-scale-400a4b#code

Buscar Missing Index

Query en SQLServer para saber que indices crear:

  1. SELECT CAST(SERVERPROPERTY('ServerName') AS [nvarchar](256)) AS [SQLServer]
  2. ,db.[database_id] AS [DatabaseID]
  3. ,db.[name] AS [DatabaseName]
  4. ,id.[object_id] AS [ObjectID]
  5. ,id.[statement] AS [FullyQualifiedObjectName]
  6. ,id.[equality_columns] AS [EqualityColumns]
  7. ,id.[inequality_columns] AS [InEqualityColumns]
  8. ,id.[included_columns] AS [IncludedColumns]
  9. ,gs.[unique_compiles] AS [UniqueCompiles]
  10. ,gs.[user_seeks] AS [UserSeeks]
  11. ,gs.[user_scans] AS [UserScans]
  12. ,gs.[last_user_seek] AS [LastUserSeekTime]
  13. ,gs.[last_user_scan] AS [LastUserScanTime]
  14. ,gs.[avg_total_user_cost] AS [AvgTotalUserCost]
  15. ,gs.[avg_user_impact] AS [AvgUserImpact]
  16. ,gs.[system_seeks] AS [SystemSeeks]
  17. ,gs.[system_scans] AS [SystemScans]
  18. ,gs.[last_system_seek] AS [LastSystemSeekTime]
  19. ,gs.[last_system_scan] AS [LastSystemScanTime]
  20. ,gs.[avg_total_system_cost] AS [AvgTotalSystemCost]
  21. ,gs.[avg_system_impact] AS [AvgSystemImpact]
  22. ,gs.[user_seeks] * gs.[avg_total_user_cost] * (gs.[avg_user_impact] * 0.01) AS [IndexAdvantage]
  23. ,'CREATE INDEX [Missing_IXNC_' + OBJECT_NAME(id.[object_id], db.[database_id]) + '_' + REPLACE(REPLACE(REPLACE(ISNULL(id.[equality_columns], ''), ', ', '_'), '[', ''), ']', '') + CASE
  24. WHEN id.[equality_columns] IS NOT NULL
  25. AND id.[inequality_columns] IS NOT NULL
  26. THEN '_'
  27. ELSE ''
  28. END + REPLACE(REPLACE(REPLACE(ISNULL(id.[inequality_columns], ''), ', ', '_'), '[', ''), ']', '') + '_' + LEFT(CAST(NEWID() AS [nvarchar](64)), 5) + ']' + ' ON ' + id.[statement] + ' (' + ISNULL(id.[equality_columns], '') + CASE
  29. WHEN id.[equality_columns] IS NOT NULL
  30. AND id.[inequality_columns] IS NOT NULL
  31. THEN ','
  32. ELSE ''
  33. END + ISNULL(id.[inequality_columns], '') + ')' + ISNULL(' INCLUDE (' + id.[included_columns] + ')', '') AS [ProposedIndex]
  34. ,CAST(CURRENT_TIMESTAMP AS [smalldatetime]) AS [CollectionDate]
  35. FROM [sys].[dm_db_missing_index_group_stats] gs WITH (NOLOCK)
  36. INNER JOIN [sys].[dm_db_missing_index_groups] ig WITH (NOLOCK)
  37. ON gs.[group_handle] = ig.[index_group_handle]
  38. INNER JOIN [sys].[dm_db_missing_index_details] id WITH (NOLOCK)
  39. ON ig.[index_handle] = id.[index_handle]
  40. INNER JOIN [sys].[DATABASES] db WITH (NOLOCK)
  41. ON db.[database_id] = id.[database_id]
  42. WHERE id.[database_id] &amp;gt; 4 -- Remove this to see for entire instance
  43. ORDER BY [IndexAdvantage] DESC
  44. OPTION (RECOMPILE);