Samsung Washmachine read status from json "SOLVED"  [Solved]

Easy to use, 100% Lua-based event scripting framework.

Moderator: leecollings

Tjeerd13
Posts: 34
Joined: Thursday 07 May 2015 16:57
Target OS: Raspberry Pi / ODroid
Domoticz version: Beta
Location: Assen
Contact:

Samsung Washmachine read status from json "SOLVED"

Post by Tjeerd13 »

This is my first dzVents script to get the status from the samsung wasmachine (https://developer.samsung.com/smartthings) . I get most of the Json data in to virtual switches. But there are some tings i cant find out.

For the wm_status i use .checkFirst() so the log of the divices show only state changes. How can i use that for the text switches so only the message is updated when there is an change. i got now a lot of log pages with the same state.

for the WM Klaar om i get "completionTime": {"value": "2020-02-18T19:40:06.568Z"} how can i translate that to 20:40 (1 hour offset and date is not relevant)?

From the json "data" i get

Code: Select all

"data": {
            "value": "{\"payload\":{\"x.com.samsung.da.state\":\"Run\",\"x.com.samsung.da.delayEndTime\":\"00:00:00\",\"x.com.samsung.da.remainingTime\":\"01:35:00\",\"if\":[\"oic.if.baseline\",\"oic.if.a\"],\"x.com.samsung.da.progressPercentage\":\"53\",\"x.com.samsung.da.supportedProgress\":[\"None\",\"Weightsensing\",\"Wash\",\"Rinse\",\"Spin\",\"Finish\"],\"x.com.samsung.da.progress\":\"Wash\",\"rt\":[\"x.com.samsung.da.operation\"]}}"
        },
for as example the washerSpinlevel i get

Code: Select all

"washerSpinLevel": {
            "value": "1400"
The waserSpinLevel i read with local washerSpinLevel = item.json.main.washerSpinLevel.value
how can i get from data. The progressPerecentage and the remainingTime ?

Are there more sugestions to improve this script?

Code: Select all

-- assumpitions for Samsung Wasmachine Script
-- Dummy textdevices WM Programma,  WM Klaar om, WM aan het, WM Toerental, WM Resterend, WM Temperatuus.
-- Dummy on/of switch WM Status
-- API key from  https://developer.samsung.com/smartthings
-- Device ID from  https://smartthings.developer.samsung.com/docs/api-ref/st-api.html#operation/getDevices  i used postman to get the device. Making a get requrdy with https://api.smartthings.com/v1/devices/ 

local API = '1234c-abcd-1234'
local Device = '987654321'

local LOGGING = true

-- Translate Washing courses to Language Text
local Course_D0 = 'Katoen'
local Course_D1 = 'Eco Katoen'
local Course_D2 = 'Syntethisch'
local Course_D3 = 'Fijne Was'
local Course_D4 = 'Spelen+Centrifugeren'
local Course_D5 = 'Eco Trommelreiniging'
local Course_D6 = 'Beddengoed'
local Course_D7 = 'Outdoor'
local Course_D8 = 'Wol'
local Course_D9 = 'Donkere Kleding'
local Course_DA = 'Super Ecowas'
local Course_DB = 'Super Speed'
local Course_DC = '15 min Kort'
local Course_BA = 'Centrifugeren'
local Machine_Off = 'Wasmachine uit'

--Define Domoticz Switches
local WM_STATUS =  'WM Status'  --Domoitcz virtual switch ON/Off state  Washer


return {
	on = {
		timer = {
			'every 1 minutes' -- just an example to trigger the request
		},
		httpResponses = {
			'trigger' -- must match with the callback passed to the openURL command
		}
	},
	execute = function(domoticz, item, myDevice, triggerinfo)
	    
	    local wm_status = domoticz.devices(WM_STATUS)

           
		if (item.isTimer) then
			domoticz.openURL({
				url = 'https://api.smartthings.com/v1/devices/'.. Device .. '/states',
				headers = { ['Authorization'] = 'Bearer'.. API },
                method = 'GET',
				callback = 'trigger', -- see httpResponses above.
		        
			})
		end

		if (item.isHTTPResponse) then

			if (item.statusCode == 200) then
				if (item.isJSON) then
				    
					    local completionTime = item.json.main.completionTime.value                                  -- Hot to translaten 2020-02-13T21:59:00.887Z   to  21:59  
					    local switch = item.json.main.switch.value
					    local washerWaterTemperature = item.json.main.washerWaterTemperature.value
    					local washerJobState = item.json.main.washerJobState.value
	    				local washerMode = item.json.main.washerMode.value
		    			local washerSpinLevel = item.json.main.washerSpinLevel.value
			       --	    local remainingTime = item.json.main.data.value.payload              -- How to get ?
			   	    
			   	    if LOGGING then
			   	    domoticz.log('Debuggg switch:' ..  switch, domoticz.LOG_INFO)
			   	    domoticz.log('Debuggg wm_status:' .. wm_status.state, domoticz.LOG_INFO)
			   	    end
		        --	  if wm_status.state ~= ('Off') and switch ~= ('off') then  --Prevents device changes (in the log) when washer is Off and status is already off.
			   	            if switch == ('on') then 
			   	                    wm_status.switchOn().checkFirst()     --turn on domoitcz WM status switch
			   	                    domoticz.devices('WM Temperatuur').updateText(washerWaterTemperature)
					                domoticz.devices('WM Aan het').updateText(washerJobState)
				   	                domoticz.devices('WM Toerental').updateText(washerSpinLevel)
					           --     domoticz.devices('WM Resterend').updateText(remainingTime)    
					                domoticz.devices('WM Klaar om').updateText(completionTime)
					                
			   	                        if washerMode == ('Table_00_Course_D0') 
                                             then domoticz.devices('WM Programma').updateText(Course_D0) 
                                        elseif washerMode == ('Table_00_Course_D1')
                                             then domoticz.devices('WM Programma').updateText(Course_D1)
                                        elseif washerMode == ('Table_00_Course_D2')
                                             then domoticz.devices('WM Programma').updateText(Course_D2)  
                                        elseif washerMode == ('Table_00_Course_D3')
                                            then domoticz.devices('WM Programma').updateText(Course_D3)  
                                        elseif washerMode == ('Table_00_Course_D4')
                                            then domoticz.devices('WM Programma').updateText(Course_D4)  
                                        elseif washerMode == ('Table_00_Course_D5')
                                            then domoticz.devices('WM Programma').updateText(Course_D5)  
                                        elseif washerMode == ('Table_00_Course_D6')
                                            then domoticz.devices('WM Programma').updateText(Course_D6)  
                                        elseif washerMode == ('Table_00_Course_D7')
                                            then domoticz.devices('WM Programma').updateText(Course_D7)  
                                        elseif washerMode == ('Table_00_Course_D8')
                                            then domoticz.devices('WM Programma').updateText(Course_D8)  
                                        elseif washerMode == ('Table_00_Course_D9')
                                            then domoticz.devices('WM Programma').updateText(Course_D9)  
                                        elseif washerMode == ('Table_00_Course_DA')
                                            then domoticz.devices('WM Programma').updateText(Course_DA)  
                                        elseif washerMode == ('Table_00_Course_DB')
                                            then domoticz.devices('WM Programma').updateText(Course_DB)  
                                        elseif washerModee == ('Table_00_Course_DC')
                                            then domoticz.devices('WM Programma').updateText(Course_DC)  
                                        elseif washerMode == ('Table_00_Course_BA')
                                            then domoticz.devices('WM Programma').updateText(Course_BA)  end
                            else
	                        
	                        wm_status.switchOff().checkFirst()
			                domoticz.devices('WM Temperatuur').updateText(Machine_Off)
				            domoticz.devices('WM Aan het').updateText(Machine_Off)
				    	    domoticz.devices('WM Programma').updateText(Machine_Off)
				    	    domoticz.devices('WM Toerental').updateText(Machine_Off)
				    	    domoticz.devices('WM Resterend').updateText(Machine_Off)
				    	    domoticz.devices('WM Klaar om').updateText(Machine_Off)
					    
			       
					        end
				 
		            --end	
			
					
					if LOGGING then
					domoticz.log('Klaar om:' .. completionTime, domoticz.LOG_INFO)
					domoticz.log('Status:' .. switch, domoticz.LOG_INFO)
					domoticz.log('Temperatuur:' .. washerWaterTemperature, domoticz.LOG_INFO)
					domoticz.log('Aan het:' .. washerJobState, domoticz.LOG_INFO)
					domoticz.log('Programma:' .. washerMode, domoticz.LOG_INFO)
					domoticz.log('Toerental:' .. washerSpinLevel, domoticz.LOG_INFO)
			--		domoticz.log('Resterende tijd:' .. remainingTime, domoticz.LOG_INFO)
			--		domoticz.log(domoticz.utils.fromJSON(item.data))
			        end
				end
				
		else
		        if LOGGING == true then
				domoticz.log('There was a problem handling the request', domoticz.LOG_ERROR)
				domoticz.log(item, domoticz.LOG_ERROR)
				end
			end

		end
end
	
}
Dashboard.JPG
Dashboard.JPG (81.93 KiB) Viewed 7186 times
Last edited by Tjeerd13 on Friday 28 February 2020 11:57, edited 3 times in total.
Pi3, Pi4, Pi4 for Testing, Dashticz, RFXtrx433, Nest: "Thermostat V2, V3, Hello". Honywell Lyric T6R, RFXCom, KaKu, HUE, P1, Open Zwave USB,
User avatar
waaren
Posts: 6028
Joined: Tuesday 03 January 2017 14:18
Target OS: Linux
Domoticz version: Beta
Location: Netherlands
Contact:

Re: Samsung Washmachine read status from json "NOOB Quistion"

Post by waaren »

Tjeerd13 wrote: Tuesday 18 February 2020 19:37 For the wm_status i use .checkFirst() so the log of the divices show only state changes. How can i use that for the text switches so only the message is updated when there is an change. i got now a lot of log pages with the same state.

for the WM Klaar om i get "completionTime": {"value": "2020-02-18T19:40:06.568Z"} how can i translate that to 20:40 (1 hour offset and date is not relevant)?
Too many questions to answer in one pass :D So lets start with the first two..

About checkFirst() for text sensors. There is no native dzVents method for that but you can use this function

Code: Select all

local function updateTextOnlyWhenChanged( textSensorName, newText)
    local textDevice = domoticz.devices(textSensorName)
    if textDevice.text == newText then 
        return 
    else
        textDevice.updateText(newText)
    end
end
The time conversion is a bit more complicated when you are not exposed to Lua patterns yet. First the dateTimeString is split into date time components and after that these components are used to build the timestamp. Then the offset is added to the timestamp and finally the calculated timestamp is converted into a time string.

Code: Select all

local function convertTime(dateString, offset )
    local function makeTimeStamp(dateString)
        local pattern = '(%d+)%-(%d+)%-(%d+)%T(%d+):(%d+):(%d+)(%.*)' -- %d+ = 1 or more digits , %.* = 0 or more any character
        local xyear, xmonth, xday, xhour, xminute, xseconds = dateString:match(pattern) -- split the string using the pattern
        local convertedTimestamp = os.time({year = xyear, month = xmonth, day = xday, hour = xhour, min = xminute, sec = xseconds})
        return convertedTimestamp
    end
    return os.date('%H:%M:%S', makeTimeStamp(dateString) + offset )
end

domoticz.log('Converted time is ' .. convertTime("2020-02-18T19:40:06.568Z", 3600), domoticz.LOG_FORCE)
Debian buster, bullseye on RPI-4, Intel NUC.
dz Beta, Z-Wave, RFLink, RFXtrx433e, P1, Youless, Hue, Yeelight, Xiaomi, MQTT
==>> dzVents wiki
User avatar
waaren
Posts: 6028
Joined: Tuesday 03 January 2017 14:18
Target OS: Linux
Domoticz version: Beta
Location: Netherlands
Contact:

Re: Samsung Washmachine read status from json "NOOB Quistion"

Post by waaren »

As requested; some suggestions in the code below.
Obviously not tested as I do not own such a fancy machine.

Any questions please feel free to ask.


Code: Select all

-- assumpitions for Samsung Wasmachine Script
-- Dummy textdevices WM Programma,  WM Klaar om, WM aan het, WM Toerental, WM Resterend, WM Temperatuus.
-- Dummy on/of switch WM Status
-- API key from  https://developer.samsung.com/smartthings
-- Device ID from  https://smartthings.developer.samsung.com/docs/api-ref/st-api.html#operation/getDevices  i used postman to get the device. Making a get requrdy with https://api.smartthings.com/v1/devices/ 

local API = '1234c-abcd-1234'
local Device = '987654321'

local LOGGING = true

--Define dz Switches
local WM_STATUS =  'WM Status'  --Domoitcz virtual switch ON/Off state  Washer


return 
{
    on = 
    {
        timer = 
        {
            'every 1 minutes', -- just an example to trigger the request
        },

        httpResponses = 
        {
            'trigger', -- must match with the callback passed to the openURL command
        },
    },
    
    logging = 
    { 
        level = domoticz.LOG_DEBUG ,
    }, 

    execute = function(dz, item)

        local wm_status = dz.devices(WM_STATUS)

        if item.isTimer then
            dz.openURL({
                url = 'https://api.smartthings.com/v1/devices/'.. Device .. '/states',
                headers = { ['Authorization'] = 'Bearer'.. API },
                method = 'GET',
                callback = 'trigger', -- see httpResponses above.
                
            })
        end

        if (item.isHTTPResponse) then
            if item.ok then
                if (item.isJSON) then
                    rt = item.json.main
                    
                    local function codeToDutch(code)
                        local translation = 
                            {
                               D0 = 'Katoen',
                               D1 = 'Eco Katoen',
                               D2 = 'Syntethisch',
                               D3 = 'Fijne Was',
                               D4 = 'Spelen+Centrifugeren',
                               D5 = 'Eco Trommelreiniging',
                               D6 = 'Beddengoed',
                               D7 = 'Outdoor',
                               D8 = 'Wol',
                               D9 = 'Donkere Kleding',
                               DA = 'Super Ecowas',
                               DB = 'Super Speed',
                               DC = '15 min Kort',
                               BA = 'Centrifugeren',
                               Machine_Off = 'Wasmachine uit',
                            }
                        return translation[code:gsub('Table_00_Course_','')] or translation[code]
                    end
                    
                    local function updateTextOnlyWhenChanged( textSensorName, newText)
                        local textDevice = dz.devices(textSensorName)
                        if textDevice.text == newText then 
                            return 
                        else
                            textDevice.updateText(newText)
                        end
                    end
                    
                    local function convertTime(dateString, offset )
                        local function makeTimeStamp(dateString)
                            local pattern = '(%d+)%-(%d+)%-(%d+)%T(%d+):(%d+):(%d+)(%.*)' -- %d+ = 1 or more digits , %.* = 0 or more any character
                            local xyear, xmonth, xday, xhour, xminute, xseconds = dateString:match(pattern) -- split the string using the pattern
                            local convertedTimestamp = os.time({year = xyear, month = xmonth, day = xday, hour = xhour, min = xminute, sec = xseconds})
                            return convertedTimestamp
                        end
                        return os.date('%H:%M:%S', makeTimeStamp(dateString) + offset )
                    end

                    local completionTime = convertTime(rt.completionTime.value, 3600 )

                    local switch = rt.switch.value
                    local washerWaterTemperature = rt.washerWaterTemperature.value
                    local washerJobState = rt.washerJobState.value
                    local washerMode = rt.washerMode.value
                    local washerSpinLevel = rt.washerSpinLevel.value
                    -- local remainingTime = rt.data.value.payload              -- How to get ?
                    
                    dz.utils.dumpTable(rt) -- this will show how the table is structured
                    
                    dz.log('Debuggg switch:' ..  switch, dz.LOG_DEBUG)
                    dz.log('Debuggg wm_status:' .. wm_status.state, dz.LOG_DEBUG)
                    if wm_status.state ~= ('Off') and switch ~= ('off') then  --Prevents device changes (in the log) when washer is Off and status is already off.
                        if switch == ('on') then 
                            wm_status.switchOn().checkFirst()     --turn on dz WM status switch
                            
                            updateTextOnlyWhenChanged('WM Temperatuur', washerWaterTemperature )
                            updateTextOnlyWhenChanged('WM Aan het', washerJobState )
                            updateTextOnlyWhenChanged('WM Temperatuur',washerSpinLevel )
                            updateTextOnlyWhenChanged('WM Toerental', washerSpinLevel)
                            updateTextOnlyWhenChanged('WM Resterend', remainingTime )
                            updateTextOnlyWhenChanged('WM Klaar om', completionTime )
                            updateTextOnlyWhenChanged('WM Programma', codeToDutch(washerMode)) 
                            if washerMode == 'Machine_Off' then 
                                wm_status.switchOff().checkFirst()
                                washerMode = codeToDutch(washerMode)
                                updateTextOnlyWhenChanged('WM Temperatuur', washerMode)
                                updateTextOnlyWhenChanged('WM Aan het', washerMode)
                                updateTextOnlyWhenChanged('WM Toerental', washerMode)
                                updateTextOnlyWhenChanged('WM Resterend', washerMode)
                                updateTextOnlyWhenChanged('WM Klaar om', washerMode)
                            end
                            
                            if LOGGING then
                                dz.log('Klaar om:' .. completionTime, dz.LOG_INFO)
                                dz.log('Status:' .. switch, dz.LOG_INFO)
                                dz.log('Temperatuur:' .. washerWaterTemperature, dz.LOG_INFO)
                                dz.log('Aan het:' .. washerJobState, dz.LOG_INFO)
                                dz.log('Programma:' .. washerMode, dz.LOG_INFO)
                                dz.log('Toerental:' .. washerSpinLevel, dz.LOG_INFO)
                        --        dz.log('Resterende tijd:' .. remainingTime, dz.LOG_INFO)
                        --        dz.log(dz.utils.fromJSON(item.data))
                            end
                        end
                    end
                elseif LOGGING == true then
                    dz.log('There was a problem handling the request', dz.LOG_ERROR)
                    dz.log(item, dz.LOG_ERROR)
                end
            end
        end
    end
}
Debian buster, bullseye on RPI-4, Intel NUC.
dz Beta, Z-Wave, RFLink, RFXtrx433e, P1, Youless, Hue, Yeelight, Xiaomi, MQTT
==>> dzVents wiki
Tjeerd13
Posts: 34
Joined: Thursday 07 May 2015 16:57
Target OS: Raspberry Pi / ODroid
Domoticz version: Beta
Location: Assen
Contact:

Re: Samsung Washmachine read status from json "NOOB Quistion"

Post by Tjeerd13 »

Thanks all for the suggestions en code. I will try them in the evening.. I gues more questions are comming :)
Pi3, Pi4, Pi4 for Testing, Dashticz, RFXtrx433, Nest: "Thermostat V2, V3, Hello". Honywell Lyric T6R, RFXCom, KaKu, HUE, P1, Open Zwave USB,
Tjeerd13
Posts: 34
Joined: Thursday 07 May 2015 16:57
Target OS: Raspberry Pi / ODroid
Domoticz version: Beta
Location: Assen
Contact:

Re: Samsung Washmachine read status from json "NOOB Question"

Post by Tjeerd13 »

After some modification of the code from Waaren its working:
Spoiler: show
-- assumpitions for Samsung Wasmachine Script
-- Dummy textdevices WM Programma, WM Klaar om, WM aan het, WM Toerental, WM Resterend, WM Temperatuus.
-- Dummy on/of switch WM Status
-- API key from https://developer.samsung.com/smartthings
-- Device ID from https://smartthings.developer.samsung.c ... getDevices i used postman to get the device. Making a get requrdy with https://api.smartthings.com/v1/devices/

local API = '1234-abcd'
local Device = '1234-abcd'


local LOGGING = true

-- Translate Washing courses to Language Text
local Course_D0 = 'Katoen'
local Course_D1 = 'Eco Katoen'
local Course_D2 = 'Syntethisch'
local Course_D3 = 'Fijne Was'
local Course_D4 = 'Spelen+Centrifugeren'
local Course_D5 = 'Eco Trommelreiniging'
local Course_D6 = 'Beddengoed'
local Course_D7 = 'Outdoor'
local Course_D8 = 'Wol'
local Course_D9 = 'Donkere Kleding'
local Course_DA = 'Super Ecowas'
local Course_DB = 'Super Speed'
local Course_DC = '15 min Kort'
local Course_BA = 'Centrifugeren'
local Machine_Off = 'Wasmachine uit'

--Define Domoticz Switches
local WM_STATUS = 'WM Status' --Domoitcz virtual switch ON/Off state Washer


return {
on = {
timer = {
'every 1 minutes' -- just an example to trigger the request
},
httpResponses = {
'trigger' -- must match with the callback passed to the openURL command
}
},
execute = function(domoticz, item, myDevice, triggerinfo)

local wm_status = domoticz.devices(WM_STATUS)


if (item.isTimer) then
domoticz.openURL({
url = 'https://api.smartthings.com/v1/devices/'.. Device .. '/states',
headers = { ['Authorization'] = 'Bearer '.. API },
method = 'GET',
callback = 'trigger', -- see httpResponses above.

})
end

if (item.isHTTPResponse) then

if (item.statusCode == 200) then
if (item.isJSON) then

local completionTime = item.json.main.completionTime.value -- Hot to translaten 2020-02-13T21:59:00.887Z to 21:59
local switch = item.json.main.switch.value
local washerWaterTemperature = item.json.main.washerWaterTemperature.value
local washerJobState = item.json.main.washerJobState.value
local washerMode = item.json.main.washerMode.value
local washerSpinLevel = item.json.main.washerSpinLevel.value
-- local remainingTime = rt.data.value['\payload']['\x.com.samsung.da.remainingTime'] --? How to get?
-- local progressPercentage = rt.data.value.payload['x.com.samsung.da.progressPercentage'] --? How to get?

if LOGGING then
domoticz.log('Debuggg switch:' .. switch, domoticz.LOG_INFO)
domoticz.log('Debuggg wm_status:' .. wm_status.state, domoticz.LOG_INFO)
end
if wm_status.state ~= ('Off') and switch ~= ('off') then --Prevents device changes (in the log) when washer is Off and status is already off.
if switch == ('on') then
wm_status.switchOn().checkFirst() --turn on domoitcz WM status switch
domoticz.devices('WM Temperatuur').updateText(washerWaterTemperature)
domoticz.devices('WM Aan het').updateText(washerJobState)
domoticz.devices('WM Toerental').updateText(washerSpinLevel)
-- domoticz.devices('WM Resterend').updateText(remainingTime)
domoticz.devices('WM Klaar om').updateText(completionTime)

if washerMode == ('Table_00_Course_D0')
then domoticz.devices('WM Programma').updateText(Course_D0)
elseif washerMode == ('Table_00_Course_D1')
then domoticz.devices('WM Programma').updateText(Course_D1)
elseif washerMode == ('Table_00_Course_D2')
then domoticz.devices('WM Programma').updateText(Course_D2)
elseif washerMode == ('Table_00_Course_D3')
then domoticz.devices('WM Programma').updateText(Course_D3)
elseif washerMode == ('Table_00_Course_D4')
then domoticz.devices('WM Programma').updateText(Course_D4)
elseif washerMode == ('Table_00_Course_D5')
then domoticz.devices('WM Programma').updateText(Course_D5)
elseif washerMode == ('Table_00_Course_D6')
then domoticz.devices('WM Programma').updateText(Course_D6)
elseif washerMode == ('Table_00_Course_D7')
then domoticz.devices('WM Programma').updateText(Course_D7)
elseif washerMode == ('Table_00_Course_D8')
then domoticz.devices('WM Programma').updateText(Course_D8)
elseif washerMode == ('Table_00_Course_D9')
then domoticz.devices('WM Programma').updateText(Course_D9)
elseif washerMode == ('Table_00_Course_DA')
then domoticz.devices('WM Programma').updateText(Course_DA)
elseif washerMode == ('Table_00_Course_DB')
then domoticz.devices('WM Programma').updateText(Course_DB)
elseif washerModee == ('Table_00_Course_DC')
then domoticz.devices('WM Programma').updateText(Course_DC)
elseif washerMode == ('Table_00_Course_BA')
then domoticz.devices('WM Programma').updateText(Course_BA) end
else

wm_status.switchOff().checkFirst()
domoticz.devices('WM Temperatuur').updateText(Machine_Off)
domoticz.devices('WM Aan het').updateText(Machine_Off)
domoticz.devices('WM Programma').updateText(Machine_Off)
domoticz.devices('WM Toerental').updateText(Machine_Off)
domoticz.devices('WM Resterend').updateText(Machine_Off)
domoticz.devices('WM Klaar om').updateText(Machine_Off)


end end

--end


if LOGGING then
domoticz.log('Klaar om:' .. completionTime, domoticz.LOG_INFO)
domoticz.log('Status:' .. switch, domoticz.LOG_INFO)
domoticz.log('Temperatuur:' .. washerWaterTemperature, domoticz.LOG_INFO)
domoticz.log('Aan het:' .. washerJobState, domoticz.LOG_INFO)
domoticz.log('Programma:' .. washerMode, domoticz.LOG_INFO)
domoticz.log('Toerental:' .. washerSpinLevel, domoticz.LOG_INFO)
-- domoticz.log('Resterende tijd:' .. remainingTime, domoticz.LOG_INFO)
-- domoticz.log(domoticz.utils.fromJSON(item.data))
end
end

else
if LOGGING == true then
domoticz.log('There was a problem handling the request', domoticz.LOG_ERROR)
domoticz.log(item, domoticz.LOG_ERROR)
end
end

end
end

}
The "If switch on" and "if switch off" was not working i used; "if switch on..... else .. end.
Adding extra space in headers = { ['Authorization'] = 'Bearer '.. API },

I can't figure out how to get info fram the .data string.


2020-02-23 18:38:00.984 Status: dzVents: > data:
2020-02-23 18:38:00.984 Status: dzVents: > value: {"payload":{"x.com.samsung.da.state":"Run","x.com.samsung.da.delayEndTime":"00:00:00","x.com.samsung.da.remainingTime":"00:24:00","if":["oic.if.baseline","oic.if.a"],"x.com.samsung.da.progressPercentage":"89","x.com.samsung.da.supportedProgress":["None","Weightsensing","Wash","Rinse","Spin","Finish"],"x.com.samsung.da.progress":"Rinse","rt":["x.com.samsung.da.operation"]}}
2020-02-23 18:38:00.984 Status: dzVents: > completionTime:
2020-02-23 18:38:00.984 Status: dzVents: > value: 2020-02-23T18:01:27.688Z

From postman:

Code: Select all

"data": {
            "value": "{\"payload\":{\"x.com.samsung.da.state\":\"Run\",\"x.com.samsung.da.delayEndTime\":\"00:00:00\",\"x.com.samsung.da.remainingTime\":\"00:21:00\",\"if\":[\"oic.if.baseline\",\"oic.if.a\"],\"x.com.samsung.da.progressPercentage\":\"90\",\"x.com.samsung.da.supportedProgress\":[\"None\",\"Weightsensing\",\"Wash\",\"Rinse\",\"Spin\",\"Finish\"],\"x.com.samsung.da.progress\":\"Rinse\",\"rt\":[\"x.com.samsung.da.operation\"]}}"
        },


x.com.samsung.da.remainingTime":"00:24:00 ??
"x.com.samsung.da.progressPercentage":"89" ??

Thanks ferry much for the code. I'm learning a lot at this way.
Pi3, Pi4, Pi4 for Testing, Dashticz, RFXtrx433, Nest: "Thermostat V2, V3, Hello". Honywell Lyric T6R, RFXCom, KaKu, HUE, P1, Open Zwave USB,
Tjeerd13
Posts: 34
Joined: Thursday 07 May 2015 16:57
Target OS: Raspberry Pi / ODroid
Domoticz version: Beta
Location: Assen
Contact:

Re: Samsung Washmachine read status from json "Working so far" trouble getting json data query

Post by Tjeerd13 »

From stackoverflow i found out that the json string is a weird construction: a serialized JSON inside a normal JSON.
This means i have to invoke deserialization twice:

Code: Select all

local json = require"json"  -- the JSON library
local outer = json.decode(your_JSON_string)
local rt = outer.main
local inner = json.decode(rt.data.value)
local remainingTime = inner.payload['x.com.samsung.da.remainingTime']
But stil no clue how te adjust the code to get this done. I added a short test version if my script for debugging.
Spoiler: show
local API = 'API'
local Device = 'Device'


local LOGGING = true

--Define dz Switches
local WM_STATUS = 'WM Status' --Domoitcz virtual switch ON/Off state Washer


return
{
on =
{
timer =
{
'every 1 minutes', -- just an example to trigger the request
},

httpResponses =
{
'trigger', -- must match with the callback passed to the openURL command
},
},

logging =
{
level = domoticz.LOG_DEBUG ,
},

execute = function(dz, item)

local wm_status = dz.devices(WM_STATUS)

if item.isTimer then
dz.openURL({
url = 'https://api.smartthings.com/v1/devices/'.. Device .. '/states',
headers = { ['Authorization'] = 'Bearer '.. API },
method = 'GET',
callback = 'trigger', -- see httpResponses above.

})
end

if (item.isHTTPResponse) then
if item.ok then
if (item.isJSON) then


rt = item.json.main
-- outer = json.decode'{"payload":{"x.com.samsung.da.state":"Run","x.com.samsung.da.delayEndTime":"00:00:00","x.com.samsung.da.remainingTime":"00:40:00","if":["oic.if.baseline","oic.if.a"],"x.com.samsung.da.progressPercentage":"81","x.com.samsung.da.supportedProgress":["None","Weightsensing","Wash","Rinse","Spin","Finish"],"x.com.samsung.da.progress":"Rinse","rt":["x.com.samsung.da.operation"]}}
inner = json.decode(rt.data.value)
-- local remainingTime = inner.payload['x.com.samsung.da.remainingTime']


dz.utils.dumpTable(rt) -- this will show how the table is structured
-- dz.utils.dumpTable(inner)

local washerSpinLevel = rt.washerSpinLevel.value
-- local remainingTime = inner.payload['x.com.samsung.da.remainingTime']




dz.log('Debuggg washerSpinLevel:' .. washerSpinLevel, dz.LOG_DEBUG)
dz.log('Debuggg remainingTime:' .. remainingTime, dz.LOG_DEBUG)

-- dz.log('Resterende tijd:' .. remainingTime, dz.LOG_INFO)
-- dz.log(dz.utils.fromJSON(item.data))


-- end
elseif LOGGING == true then
dz.log('There was a problem handling the request', dz.LOG_ERROR)
dz.log(item, dz.LOG_ERROR)
end
end
end
end
}[/spolier]]
Pi3, Pi4, Pi4 for Testing, Dashticz, RFXtrx433, Nest: "Thermostat V2, V3, Hello". Honywell Lyric T6R, RFXCom, KaKu, HUE, P1, Open Zwave USB,
User avatar
waaren
Posts: 6028
Joined: Tuesday 03 January 2017 14:18
Target OS: Linux
Domoticz version: Beta
Location: Netherlands
Contact:

Re: Samsung Washmachine read status from json "Working so far" trouble getting json data query

Post by waaren »

Tjeerd13 wrote: Monday 24 February 2020 20:33 From stackoverflow i found out that the json string is a weird construction: a serialized JSON inside a normal JSON.
This means i have to invoke deserialization twice:
There should not be a need to do that. Can you share the complete return from your openURL call ?

You can print it to log with the line

Code: Select all

dz.log(item.data,dz.LOG_FORCE)
Debian buster, bullseye on RPI-4, Intel NUC.
dz Beta, Z-Wave, RFLink, RFXtrx433e, P1, Youless, Hue, Yeelight, Xiaomi, MQTT
==>> dzVents wiki
Tjeerd13
Posts: 34
Joined: Thursday 07 May 2015 16:57
Target OS: Raspberry Pi / ODroid
Domoticz version: Beta
Location: Assen
Contact:

Re: Samsung Washmachine read status from json "Working so far" trouble getting json data query

Post by Tjeerd13 »

Below is the return of the openURL call when the wasmachine is on:
Spoiler: show
!Info: {"main":{"washerAutoSoftener":{"value":null},"mndt":{"value":null},"mnfv":{"value":"0.1.0"},"washerAddwashAlarm":{"value":null},"mnhw":{"value":"1.0"},"data":{"value":"{\"payload\":{\"x.com.samsung.da.state\":\"Run\",\"x.com.samsung.da.delayEndTime\":\"00:00:00\",\"x.com.samsung.da.remainingTime\":\"01:24:00\",\"if\":[\"oic.if.baseline\",\"oic.if.a\"],\"x.com.samsung.da.progressPercentage\":\"2\",\"x.com.samsung.da.supportedProgress\":[\"None\",\"Weightsensing\",\"Wash\",\"Rinse\",\"Spin\",\"Finish\"],\"x.com.samsung.da.progress\":\"Wash\",\"rt\":[\"x.com.samsung.da.operation\"]}}"},"di":{"value":"2a32e8fd-a11c-b3e4-a321-24b99d2bf796"},"washerSpinLevel":{"value":"1400"},"mnsl":{"value":null},"washerMode":{"value":"Table_00_Course_D0"},"error":{"value":null},"dmv":{"value":"res.1.1.0,sh.1.1.0"},"washerRinseCycles":{"value":"2"},"switch":{"value":"on"},"vid":{"value":"DA-WM-WM-000001"},"completionTime":{"value":"2020-02-25T11:34:47.718Z"},"washerJobState":{"value":"wash"},"mnpv":{"value":"0.1.0"},"supportedWasherWaterTemperature":{"value":"[\"none\",\"cold\",\"20\",\"30\",\"40\",\"60\",\"90\"]"},"washerWaterTemperature":{"value":"40"},"icv":{"value":"core.1.1.0"},"supportedWasherSpinLevel":{"value":"[\"rinseHold\",\"noSpin\",\"400\",\"800\",\"1000\",\"1200\",\"1400\"]"},"supportedWasherSoilLevel":{"value":null},"st":{"value":null},"powerConsumption":{"value":"{\"deltaEnergy\":0,\"power\":0,\"energy\":217200}"},"machineState":{"value":"run"},"disabledCapabilities":{"value":"[\"custom.washerAutoDetergent\",\"custom.washerAutoSoftener\",\"custom.washerSoilLevel\",\"custom.washerAddwashAlarm\",\"powerConsumptionReport\"]"},"versionNumber":{"value":"19102401"},"n":{"value":"[washer] Samsung"},"mnmo":{"value":"ARTIK051_WM_COM_18K|20228841|20010102001211530203000000000000"},"washerSoilLevel":{"value":null},"mnmn":{"value":"Samsung Electronics"},"mnml":{"value":"http://www.samsung.com"},"mnos":{"value":"TizenRT2.0"},"pi":{"value":"2a32e8fd-a11c-b3e4-a321-24b99d2bf796"},"supportedMachineStates":{"value":null},"remoteControlEnabled":{"value":"true"},"washerAutoDetergent":{"value":null},"supportedWasherRinseCycles":{"value":"[0,1,2,3,4,5]"},"supportedCourses":{"value":"[\"D0\",\"DC\",\"DB\",\"DA\",\"D9\",\"D8\",\"D7\",\"D6\",\"D5\",\"BA\",\"D4\",\"D3\",\"D2\",\"D1\"]"}}}
This one is when the wasmachine is off
Spoiler: show
!Info: {"main":{"washerAutoSoftener":{"value":null},"mndt":{"value":null},"mnfv":{"value":"0.1.0"},"washerAddwashAlarm":{"value":null},"mnhw":{"value":"1.0"},"data":{"value":"{\"payload\":{\"x.com.samsung.da.options\":[\"AvailableDelayTime_85\"],\"if\":[\"oic.if.baseline\",\"oic.if.a\"],\"rt\":[\"x.com.samsung.da.mode\"]}}"},"di":{"value":"2a32e8fd-a11c-b3e4-a321-24b99d2bf796"},"washerSpinLevel":{"value":"1400"},"mnsl":{"value":null},"washerMode":{"value":"Table_00_Course_D0"},"error":{"value":null},"dmv":{"value":"res.1.1.0,sh.1.1.0"},"washerRinseCycles":{"value":"2"},"switch":{"value":"off"},"vid":{"value":"DA-WM-WM-000001"},"completionTime":{"value":"2020-02-24T21:01:10.363Z"},"washerJobState":{"value":"none"},"mnpv":{"value":"0.1.0"},"supportedWasherWaterTemperature":{"value":"[\"none\",\"cold\",\"20\",\"30\",\"40\",\"60\",\"90\"]"},"washerWaterTemperature":{"value":"40"},"icv":{"value":"core.1.1.0"},"supportedWasherSpinLevel":{"value":"[\"rinseHold\",\"noSpin\",\"400\",\"800\",\"1000\",\"1200\",\"1400\"]"},"supportedWasherSoilLevel":{"value":null},"st":{"value":null},"powerConsumption":{"value":"{\"deltaEnergy\":0,\"power\":0,\"energy\":217200}"},"machineState":{"value":"stop"},"disabledCapabilities":{"value":"[\"custom.washerAutoDetergent\",\"custom.washerAutoSoftener\",\"custom.washerSoilLevel\",\"custom.washerAddwashAlarm\",\"powerConsumptionReport\"]"},"versionNumber":{"value":"19102401"},"n":{"value":"[washer] Samsung"},"mnmo":{"value":"ARTIK051_WM_COM_18K|20228841|20010102001211530203000000000000"},"washerSoilLevel":{"value":null},"mnmn":{"value":"Samsung Electronics"},"mnml":{"value":"http://www.samsung.com"},"mnos":{"value":"TizenRT2.0"},"pi":{"value":"2a32e8fd-a11c-b3e4-a321-24b99d2bf796"},"supportedMachineStates":{"value":null},"remoteControlEnabled":{"value":"false"},"washerAutoDetergent":{"value":null},"supportedWasherRinseCycles":{"value":"[0,1,2,3,4,5]"},"supportedCourses":{"value":"[\"D0\",\"DC\",\"DB\",\"DA\",\"D9\",\"D8\",\"D7\",\"D6\",\"D5\",\"BA\",\"D4\",\"D3\",\"D2\",\"D1\"]"}}}
The data value progressPercentage and remainingTime is only there when the washer is on. My gues is that with "if switch == ('on') then " that is not generating any errors.
Pi3, Pi4, Pi4 for Testing, Dashticz, RFXtrx433, Nest: "Thermostat V2, V3, Hello". Honywell Lyric T6R, RFXCom, KaKu, HUE, P1, Open Zwave USB,
User avatar
waaren
Posts: 6028
Joined: Tuesday 03 January 2017 14:18
Target OS: Linux
Domoticz version: Beta
Location: Netherlands
Contact:

Re: Samsung Washmachine read status from json "Working so far" trouble getting json data query

Post by waaren »

Tjeerd13 wrote: Tuesday 25 February 2020 11:17 Below is the return of the openURL call when the wasmachine is on:
See below the basic script to get all values in table. From there it should be easy to fill the domoticz sensors / switches and vars.

Code: Select all

local API = 'xxxxxxxxx'
local Device = 'xxxxxxxx'
local scriptVar = 'wasmachine_JSON'

return 
{
    on = 
    {
        timer = 
        {
            'every minute', -- just an example to trigger the request
        },

        httpResponses = 
        {
            scriptVar, -- must match with the callback passed to the openURL command
        },
    },
    
    logging = 
    { 
        level = domoticz.LOG_DEBUG ,
        marker = scriptVar,
    }, 

    execute = function(dz, item)

        if item.isTimer or item.isDevice then
            dz.openURL({
                url = 'https://api.smartthings.com/v1/devices/'.. Device .. '/states',
                headers = { ['Authorization'] = 'Bearer '.. API },
                method = 'GET',
                callback = scriptVar, -- httpResponses above.
            })
            return
        elseif item.ok then
            if (item.isJSON) then -- when recognized as json then dzVents will convert it to a table for you
                dz.utils.dumpTable(item.json) -- dump the string represenation of the complete table to log 
                
                dz.log('\n-\nAnd now some subtables \n-\n ', dz.LOG_DEBUG)
                
                dz.log('\n-\n ------------  main.supportedWasherSpinLevel.value\n-\n', dz.LOG_DEBUG)
                dz.utils.dumpTable(dz.utils.fromJSON(item.json.main.supportedWasherSpinLevel.value))
                
                dz.log('\n-\n ------------  main.data.value\n-\n', dz.LOG_DEBUG)
                dz.utils.dumpTable(dz.utils.fromJSON(item.json.main.data.value))
                
                dz.log('\n-\n ------------  main.disabledCapabilities.value\n-\n', dz.LOG_DEBUG)
                dz.utils.dumpTable(dz.utils.fromJSON(item.json.main.disabledCapabilities.value))
                return
            else
                dz.log('result was not recognized as a JSON', dz.LOG_ERROR)
            end
        else
            dz.log('result was not OK', dz.LOG_ERROR)
        end
        dz.log(item,dz.LOG_ERROR) -- dump all to log as one long string
    end
}
producing this output
Spoiler: show

Code: Select all

: Info: wasmachine_JSON: ------ Start internal script: Samsung washing machine:, trigger: "every minute"
: Debug: wasmachine_JSON: OpenURL: url = https://api.smartthings.com/v1/devices/XXXXXXXXXXXXX/states
: Debug: wasmachine_JSON: OpenURL: method = GET
: Debug: wasmachine_JSON: OpenURL: post data = nil
: Debug: wasmachine_JSON: OpenURL: headers = {["Authorization"]="Bearer XXXXXXXXXXXXXXXXX"}
: Debug: wasmachine_JSON: OpenURL: callback = wasmachine_JSON
: Info: wasmachine_JSON: ------ Finished Samsung washing machine

: Info: Handling httpResponse-events for: "wasmachine_JSON"
: Info: wasmachine_JSON: ------ Start internal script: Samsung washing machine: HTTPResponse: "wasmachine_JSON"
: > main:
: >     di:
: >             value: 2a32e8fd-a11c-b3e4-a321-24b99d2bf796
: >     mnmn:
: >             value: Samsung Electronics
: >     mnpv:
: >             value: 0.1.0
: >     washerMode:
: >             value: Table_00_Course_D0
: >     completionTime:
: >             value: 2020-02-25T13:34:14.299Z
: >     washerAutoDetergent:
: >     supportedWasherSpinLevel:
: >             value: ["rinseHold","noSpin","400","800","1000","1200","1400"]
: >     powerConsumption:
: >             value: {"deltaEnergy":0,"power":0,"energy":217500}
: >     remoteControlEnabled:
: >             value: true
: >     washerWaterTemperature:
: >             value: 40
: >     mnfv:
: >             value: 0.1.0
: >     st:
: >     supportedWasherSoilLevel:
: >     machineState:
: >             value: run
: >     supportedWasherWaterTemperature:
: >             value: ["none","cold","20","30","40","60","90"]
: >     washerAutoSoftener:
: >     mndt:
: >     washerSpinLevel:
: >             value: 1400
: >     washerAddwashAlarm:
: >     data:
: >             value: {"payload":{"jobStates":["None","Weightsensing","Wash","Rinse","Spin","Finish"],"currentJobState":"Rinse","if":["oic.if.baseline","oic.if.a"],"remainingTime":"00:40:00","rt":["oic.r.operational.state"],"progressPercentage":"81","currentMachineState":"active","machineStates":["pause","active","idle"]}}
: >     mnmo:
: >             value: ARTIK051_WM_COM_18K|20228841|20010102001211530203000000000000
: >     supportedMachineStates:
: >     icv:
: >             value: core.1.1.0
: >     mnhw:
: >             value: 1.0
: >     switch:
: >             value: on
: >     supportedCourses:
: >             value: ["D0","DC","DB","DA","D9","D8","D7","D6","D5","BA","D4","D3","D2","D1"]
: >     supportedWasherRinseCycles:
: >             value: [0,1,2,3,4,5]
: >     pi:
: >             value: 2a32e8fd-a11c-b3e4-a321-24b99d2bf796
: >     n:
: >             value: [washer] Samsung
: >     mnml:
: >             value: http://www.samsung.com
: >     versionNumber:
: >             value: 19102401
: >     mnos:
: >             value: TizenRT2.0
: >     disabledCapabilities:
: >             value: ["custom.washerAutoDetergent","custom.washerAutoSoftener","custom.washerSoilLevel","custom.washerAddwashAlarm","powerConsumptionReport"]
: >     error:
: >     mnsl:
: >     washerSoilLevel:
: >     washerRinseCycles:
: >             value: 3
: >     dmv:
: >             value: res.1.1.0,sh.1.1.0
: >     vid:
: >             value: DA-WM-WM-000001
: >     washerJobState:
: >             value: rinse

And now some subtables
 ------------  main.supportedWasherSpinLevel.value

: > 1: rinseHold
: > 2: noSpin
: > 3: 400
: > 4: 800
: > 5: 1000
: > 6: 1200
: > 7: 1400
: Debug: wasmachine_JSON:

 ------------  main.data.value

: > payload:
: >     remainingTime: 00:40:00
: >     machineStates:
: >             1: pause
: >             2: active
: >             3: idle
: >     jobStates:
: >             1: None
: >             2: Weightsensing
: >             3: Wash
: >             4: Rinse
: >             5: Spin
: >             6: Finish
: >     currentJobState: Rinse
: >     currentMachineState: active
: >     rt:
: >             1: oic.r.operational.state
: >     progressPercentage: 81
: >     if:
: >             1: oic.if.baseline
: >             2: oic.if.a

 ------------  main.disabledCapabilities.value

: > 1: custom.washerAutoDetergent
: > 2: custom.washerAutoSoftener
: > 3: custom.washerSoilLevel
: > 4: custom.washerAddwashAlarm
: > 5: powerConsumptionReport

: Info: wasmachine_JSON: ------ Finished Samsung washing machine

Debian buster, bullseye on RPI-4, Intel NUC.
dz Beta, Z-Wave, RFLink, RFXtrx433e, P1, Youless, Hue, Yeelight, Xiaomi, MQTT
==>> dzVents wiki
Tjeerd13
Posts: 34
Joined: Thursday 07 May 2015 16:57
Target OS: Raspberry Pi / ODroid
Domoticz version: Beta
Location: Assen
Contact:

Re: Samsung Washmachine read status from json "Working so far" trouble getting json data query

Post by Tjeerd13 »

Thanks so far,

I can't find out how to get the remainingTime:
My output of the data section is:
Spoiler: show
2020-02-25 17:43:26.267 ------------ main.data.value
2020-02-25 17:43:26.267 -
2020-02-25 17:43:26.267
2020-02-25 17:43:26.269 Status: dzVents: > payload:
2020-02-25 17:43:26.269 Status: dzVents: > x.com.samsung.da.progressPercentage: 74
2020-02-25 17:43:26.269 Status: dzVents: > if:
2020-02-25 17:43:26.269 Status: dzVents: > 1: oic.if.baseline
2020-02-25 17:43:26.269 Status: dzVents: > 2: oic.if.a
2020-02-25 17:43:26.269 Status: dzVents: > x.com.samsung.da.remainingTime: 00:54:00
2020-02-25 17:43:26.269 Status: dzVents: > rt:
2020-02-25 17:43:26.269 Status: dzVents: > 1: x.com.samsung.da.operation
2020-02-25 17:43:26.269 Status: dzVents: > x.com.samsung.da.supportedProgress:
2020-02-25 17:43:26.269 Status: dzVents: > 1: None
2020-02-25 17:43:26.269 Status: dzVents: > 2: Weightsensing
2020-02-25 17:43:26.269 Status: dzVents: > 3: Wash
2020-02-25 17:43:26.269 Status: dzVents: > 4: Rinse
2020-02-25 17:43:26.269 Status: dzVents: > 5: Spin
2020-02-25 17:43:26.269 Status: dzVents: > 6: Finish
2020-02-25 17:43:26.269 Status: dzVents: > x.com.samsung.da.progress: Rinse
2020-02-25 17:43:26.269 Status: dzVents: > x.com.samsung.da.delayEndTime: 00:00:00
2020-02-25 17:43:26.269 Status: dzVents: > x.com.samsung.da.state: Run
2020-02-25 17:43:26.269 Status: dzVents: Debug: wasmachine_JSON:
And a few seconds later:
Spoiler: show
2020-02-25 17:48:01.102 Status: dzVents: > payload:
2020-02-25 17:48:01.102 Status: dzVents: > if:
2020-02-25 17:48:01.102 Status: dzVents: > 1: oic.if.baseline
2020-02-25 17:48:01.102 Status: dzVents: > 2: oic.if.a
2020-02-25 17:48:01.102 Status: dzVents: > machineStates:
2020-02-25 17:48:01.102 Status: dzVents: > 1: pause
2020-02-25 17:48:01.102 Status: dzVents: > 2: active
2020-02-25 17:48:01.102 Status: dzVents: > 3: idle
2020-02-25 17:48:01.102 Status: dzVents: > currentMachineState: active
2020-02-25 17:48:01.102 Status: dzVents: > remainingTime: 00:49:00
2020-02-25 17:48:01.102 Status: dzVents: > jobStates:
2020-02-25 17:48:01.102 Status: dzVents: > 1: None
2020-02-25 17:48:01.102 Status: dzVents: > 2: Weightsensing
2020-02-25 17:48:01.102 Status: dzVents: > 3: Wash
2020-02-25 17:48:01.102 Status: dzVents: > 4: Rinse
2020-02-25 17:48:01.103 Status: dzVents: > 5: Spin
2020-02-25 17:48:01.103 Status: dzVents: > 6: Finish
2020-02-25 17:48:01.103 Status: dzVents: > rt:
2020-02-25 17:48:01.103 Status: dzVents: > 1: oic.r.operational.state
2020-02-25 17:48:01.103 Status: dzVents: > currentJobState: Rinse
2020-02-25 17:48:01.103 Status: dzVents: > progressPercentage: 76
2020-02-25 17:48:01.103 Status: dzVents: Debug: wasmachine_JSON:
2020-02-25 17:48:01.103 -
For :

local switch = item.json.main.switch.value
dz.log('Status:' .. switch, dz.LOG_INFO) I get the switch status.

How can i get the reaminngtime i tired a lot of things:
remainingTime = item.json.main.data.value.payload.remainingTime
remainingTime = payload.remainingTime

dz.log('Resterende tijds:' .. remainingTime, dz.LOG_INFO)

Most of the time i get: attempt to index a nil value (field 'something')
I't driving me crazy ;-)
Pi3, Pi4, Pi4 for Testing, Dashticz, RFXtrx433, Nest: "Thermostat V2, V3, Hello". Honywell Lyric T6R, RFXCom, KaKu, HUE, P1, Open Zwave USB,
User avatar
waaren
Posts: 6028
Joined: Tuesday 03 January 2017 14:18
Target OS: Linux
Domoticz version: Beta
Location: Netherlands
Contact:

Re: Samsung Washmachine read status from json "Working so far" trouble getting json data query

Post by waaren »

Tjeerd13 wrote: Tuesday 25 February 2020 17:57 Most of the time i get: attempt to index a nil value (field 'something')
I't driving me crazy ;-)
It looks like the machine is not consistent in its returns. It returns the remaining time intermittent in two different keys.
The script below looks at both keys

Code: Select all

local API = 'XXXXXXXX'
local Device = 'XXXXXXX'
local scriptVar = 'wasmachine_JSON'

return 
{
    on = 
    {
        timer = 
        {
            'every minute', -- just an example to trigger the request
        },

        httpResponses = 
        {
            scriptVar, -- must match with the callback passed to the openURL command
        },
    },
    
    logging = 
    { 
        level = domoticz.LOG_DEBUG ,
        marker = scriptVar,
    }, 

    execute = function(dz, item)

        if item.isTimer or item.isDevice then
            dz.openURL({
                url = 'https://api.smartthings.com/v1/devices/'.. Device .. '/states',
                headers = { ['Authorization'] = 'Bearer '.. API },
                method = 'GET',
                callback = scriptVar, -- httpResponses above.
            })
            return
        elseif item.ok then
            if (item.isJSON) then -- when recognized as json then dzVents will convert it to a table for you
             --[[
                dz.utils.dumpTable(item.json) -- dump the string represenation of the complete table to log 
                
                dz.log('\n-\nAnd now some subtables \n-\n ', dz.LOG_DEBUG)
                
                dz.log('\n-\n ------------  main.supportedWasherSpinLevel.value\n-\n', dz.LOG_DEBUG)
                dz.utils.dumpTable(dz.utils.fromJSON(item.json.main.supportedWasherSpinLevel.value))
                
                dz.log('\n-\n ------------  main.data.value\n-\n', dz.LOG_DEBUG)
                dz.utils.dumpTable(dz.utils.fromJSON(item.json.main.data.value))
                
                dz.log('\n-\n ------------  main.disabledCapabilities.value\n-\n', dz.LOG_DEBUG)
                dz.utils.dumpTable(dz.utils.fromJSON(item.json.main.disabledCapabilities.value))
                ]]--
                
                dz.log('\n-\n ------------  remainingTime\n-\n', dz.LOG_DEBUG)
                local values = dz.utils.fromJSON(item.json.main.data.value)
                local remainingTime = values.payload.remainingTime or  values.payload["x.com.samsung.da.remainingTime"] or 'not found'
                dz.log('remaining time = ' .. remainingTime, dz.LOG_FORCE) 
                
                return
            else
                dz.log('result was not recognized as a JSON', dz.LOG_ERROR)
            end
        else
            dz.log('result was not OK', dz.LOG_ERROR)
        end
        dz.log(item,dz.LOG_ERROR) -- dump all to log as one long string
    end
}
Debian buster, bullseye on RPI-4, Intel NUC.
dz Beta, Z-Wave, RFLink, RFXtrx433e, P1, Youless, Hue, Yeelight, Xiaomi, MQTT
==>> dzVents wiki
Tjeerd13
Posts: 34
Joined: Thursday 07 May 2015 16:57
Target OS: Raspberry Pi / ODroid
Domoticz version: Beta
Location: Assen
Contact:

Re: Samsung Washmachine read status from json "Working so far" trouble getting json data query  [Solved]

Post by Tjeerd13 »

With a lot of help from Waaren (THANKS FOR THAT ! !) below is the working script.
With a litle ToDo list.

Code: Select all

-- assumpitions for Samsung Wasmachine Script
-- Dummy textdevices WM Programma,  WM Klaar om, WM aan het, WM Toerental, WM Resterend, WM Temperatuus.
-- Dummy on/of switch WM Status
-- Dummy Percentaeg WM Percentage
-- API key from  https://developer.samsung.com/smartthings
-- Device ID from  https://smartthings.developer.samsung.com/docs/api-ref/st-api.html#operation/getDevices  i used postman to get the device. Making a get requrdy with https://api.smartthings.com/v1/devices/ 

--Thanks a lot for the help from Waaren.

--To Do List: 

--Update Percentage only when percentage is changed. No idea how to get the Percentage from Domoticz..
--Prevent showing Tables in log when dzVents loggin is set to errors only


local API = '<YOUR API>'
local Device = '<YOUR DEVICE ID>'
local scriptVar = 'wasmachine_JSON'

local LOGGING = false

--Define dz Switches
local WM_STATUS =  'WM Status'  --Domoitcz virtual switch ON/Off state  Washer




return 
{
    on = 
    {
        timer = 
        {
            'every minute', -- just an example to trigger the request
        },
        
        devices =
        {
            4,              -- Just on Switch to activated the scrpt manualy for testing.
        },
        httpResponses = 
        {
            scriptVar, -- must match with the callback passed to the openURL command
        },
    },
    
    logging = 
    { 
       -- level = domoticz.LOG_DEBUG ,
        marker = scriptVar,
    }, 

    execute = function(dz, item)
    
    local wm_status = dz.devices(WM_STATUS)

    
  
    
        if item.isTimer or item.isDevice then
            dz.openURL({
                url = 'https://api.smartthings.com/v1/devices/'.. Device .. '/states',
                headers = { ['Authorization'] = 'Bearer '.. API },
                method = 'GET',
                callback = scriptVar, -- httpResponses above.
            })
            return
        elseif item.ok then
            if (item.isJSON) then -- when recognized as json then dzVents will convert it to a table for you
                rt = item.json.main
                dz.utils.dumpTable(item.json) -- dump the string represenation of the complete table to log 
                dz.log('\n-\nAnd now some subtables \n-\n ', dz.LOG_DEBUG)
                dz.log('\n-\n ------------  main.data.value\n-\n', dz.LOG_DEBUG)
                dz.utils.dumpTable(dz.utils.fromJSON(item.json.main.data.value))  --dump the string represenation of the DATA table to log, The data atributes changes depending on the state of the washer. 
                
            
            
                local function codeToDutch(code)        --Convert Table_00_Course_* and Washingstate to Dutch
                        local translationcode = 
                            {
                               D0 = 'Katoen',
                               D1 = 'Eco Katoen',
                               D2 = 'Syntethisch',
                               D3 = 'Fijne Was',
                               D4 = 'Spelen+Centrifugeren',
                               D5 = 'Eco Trommelreiniging',
                               D6 = 'Beddengoed',
                               D7 = 'Outdoor',
                               D8 = 'Wol',
                               D9 = 'Donkere Kleding',
                               DA = 'Super Ecowas',
                               DB = 'Super Speed',
                               DC = '15 min Kort',
                               BA = 'Centrifugeren',
                               none = 'Niksen',
                               weightsensing = 'Wegen',
                               wash = 'Wassen',
                               rinse = 'Spoelen',
                               spin = 'Centrifugeren',
                               finish = 'Klaar',
                            }
                        return translationcode[code:gsub('Table_00_Course_','')] or translation[code]
                    end     
                local endprogram = 'Programma gereed'
                
                local function updateTextOnlyWhenChanged( textSensorName, newText)          --Update textdevices only when status is changed to prevent to much inrelevant log rows
                        local textDevice = dz.devices(textSensorName)
                        if textDevice.text == newText then 
                            return 
                        else
                            textDevice.updateText(newText)
                        end
                end
                
                local function convertTime(dateString, offset )                             --convert the time to Hour,Minutem,second.
                        local function makeTimeStamp(dateString)
                            local pattern = '(%d+)%-(%d+)%-(%d+)%T(%d+):(%d+):(%d+)(%.*)' -- %d+ = 1 or more digits , %.* = 0 or more any character
                            local xyear, xmonth, xday, xhour, xminute, xseconds = dateString:match(pattern) -- split the string using the pattern
                            local convertedTimestamp = os.time({year = xyear, month = xmonth, day = xday, hour = xhour, min = xminute, sec = xseconds})
                            return convertedTimestamp
                        end
                        return os.date('%H:%M:%S', makeTimeStamp(dateString) + offset )
                    end
                    
                    
                    local values = dz.utils.fromJSON(item.json.main.data.value)
                    local remainingTime = values.payload.remainingTime or  values.payload["x.com.samsung.da.remainingTime"] or 'not found'
                    local progressPercentage = values.payload.progressPercentage or  values.payload["x.com.samsung.da.progressPercentage"] or 'not found'
                    
                    
                    local completionTime = convertTime(rt.completionTime.value, 3600 )   --Making 1 hour ofset to get local time
                    local switch = rt.switch.value
                    local washerWaterTemperature = rt.washerWaterTemperature.value
                    local washerJobState = rt.washerJobState.value
                    local washerMode = rt.washerMode.value
                    local washerSpinLevel = rt.washerSpinLevel.value
                    
                    if switch == ('on') then                                            -- Turn on Domoitcz switches updates only when Washer is Active.
                            dz.log('Debuggg if swithc on:' ..  switch, dz.LOG_DEBUG)
                            wm_status.switchOn().checkFirst()     --turn on dz WM status switch
                            updateTextOnlyWhenChanged('WM Temperatuur', washerWaterTemperature )
                            updateTextOnlyWhenChanged('WM Aan het', codeToDutch(washerJobState))
                            updateTextOnlyWhenChanged('WM Toerental', washerSpinLevel)
                            updateTextOnlyWhenChanged('WM Resterend', remainingTime)
                            updateTextOnlyWhenChanged('WM Klaar om', completionTime)
                            updateTextOnlyWhenChanged('WM Programma', codeToDutch(washerMode)) 
                            dz.devices('WM Percentage').updatePercentage(progressPercentage)
                    else                                                                --Upate text deices with endprogram wen swithc is off
                                dz.log('Debuggg if switch off:' ..  switch, dz.LOG_DEBUG)
                                
                                wm_status.switchOff().checkFirst()
                                dz.log('washerMode if switch off:' ..  endprogram, dz.LOG_DEBUG)
                                updateTextOnlyWhenChanged('WM Temperatuur', endprogram)
                                updateTextOnlyWhenChanged('WM Aan het', endprogram)
                                updateTextOnlyWhenChanged('WM Toerental', endprogram)
                                updateTextOnlyWhenChanged('WM Resterend', endprogram)
                                updateTextOnlyWhenChanged('WM Klaar om', endprogram)
                                updateTextOnlyWhenChanged('WM Programma', endprogram)
                                dz.devices('WM Percentage').updatePercentage('100')
                                
                     end        
                            if LOGGING then                                             
                                dz.log('\n-\nWhats happening: \n-\n ', dz.LOG_INFO)
                                dz.log('Klaar om:' .. completionTime, dz.LOG_INFO)
                                dz.log('Status:' .. switch, dz.LOG_INFO)
                                dz.log('Temperatuur:' .. washerWaterTemperature, dz.LOG_INFO)
                                dz.log('Aan het:' .. washerJobState, dz.LOG_INFO)
                                dz.log('Programma:' .. washerMode, dz.LOG_INFO)
                                dz.log('Toerental:' .. washerSpinLevel, dz.LOG_INFO)
                                dz.log('remaining time = ' .. remainingTime, dz.LOG_INFO) 
                                dz.log('progressPercentage  = ' .. progressPercentage, dz.LOG_INFO)
                                dz.log('\n-\n============================== \n-\n ', dz.LOG_INFO)
                            end
                   
                
                
                
                return
            else
                dz.log('result was not recognized as a JSON', dz.LOG_ERROR)
            end
        else
            dz.log('result was not OK', dz.LOG_ERROR)
        end
        dz.log(item,dz.LOG_ERROR) -- dump all to log as one long string
    end
}
Dashboar OK.JPG
Dashboar OK.JPG (87.35 KiB) Viewed 7025 times
Pi3, Pi4, Pi4 for Testing, Dashticz, RFXtrx433, Nest: "Thermostat V2, V3, Hello". Honywell Lyric T6R, RFXCom, KaKu, HUE, P1, Open Zwave USB,
User avatar
waaren
Posts: 6028
Joined: Tuesday 03 January 2017 14:18
Target OS: Linux
Domoticz version: Beta
Location: Netherlands
Contact:

Re: Samsung Washmachine read status from json "Working so far" trouble getting json data query

Post by waaren »

Tjeerd13 wrote: Friday 28 February 2020 11:57 With a litle ToDo list.
prevent dump of table when not using debug log.
Only update percentage when changed.

Code: Select all

-- assumpitions for Samsung Wasmachine Script
--[[
	 Dummy textdevices WM Programma,  WM Klaar om, WM aan het, WM Toerental, WM Resterend, WM Temperatuus.
 	Dummy on/of switch WM Status
 	Dummy Percentaeg WM Percentage
 	API key from  https://developer.samsung.com/smartthings
 	Device ID from  https://smartthings.developer.samsung.com/docs/api-ref/st-api.html#operation/getDevices  i used postman to get the device. 
  	Making a get request with https://api.smartthings.com/v1/devices/ 
]]--

local API = '<YOUR API>'
local Device = '<YOUR DEVICE ID>'
local scriptVar = 'wasmachine_JSON'

--Define dz Switches
local WM_STATUS =  'WM Status'  --Domoticz virtual switch ON/Off state  Washer

local LOGGING = false

return 
{
    on = 
    {
        timer = 
        {
            'every minute', -- just an example to trigger the request
        },
        
        devices =
        {
            4,              -- Just on Switch to activated the script manualy for testing.
        },
        httpResponses = 
        {
            scriptVar, -- must match with the callback passed to the openURL command
        },
    },
    
    logging = 
    { 
        level = domoticz.LOG_ERROR,
        marker = scriptVar,
    }, 

    execute = function(dz, item)
    	local wm_status = dz.devices(WM_STATUS)

        if item.isTimer or item.isDevice then
            dz.openURL({
                url = 'https://api.smartthings.com/v1/devices/'.. Device .. '/states',
                headers = { ['Authorization'] = 'Bearer '.. API },
                method = 'GET',
                callback = scriptVar, -- httpResponses above.
            })
            return
        elseif item.ok then
            if (item.isJSON) then -- when recognized as json then dzVents will convert it to a table for you
                rt = item.json.main
                if _G.logLevel == dz.LOG_DEBUG then -- Only when script loglevel is set to debug
                    
                    -- dump the string represenation of the complete table to log 
                    dz.utils.dumpTable(item.json) 
                
                    dz.log('\n-\nAnd now some subtables \n-\n ', dz.LOG_DEBUG)
                    dz.log('\n-\n ------------  main.data.value\n-\n', dz.LOG_DEBUG)
                    
                    --dump the string representation of the DATA table to log, The data attributes changes depending on the state of the washer. 
                    dz.utils.dumpTable(dz.utils.fromJSON(item.json.main.data.value))  
                
                end
                
            
            
                local function codeToDutch(code)        --Convert Table_00_Course_* and Washingstate to Dutch
                        local translationcode = 
                            {
                               D0 = 'Katoen',
                               D1 = 'Eco Katoen',
                               D2 = 'Syntethisch',
                               D3 = 'Fijne Was',
                               D4 = 'Spelen+Centrifugeren',
                               D5 = 'Eco Trommelreiniging',
                               D6 = 'Beddengoed',
                               D7 = 'Outdoor',
                               D8 = 'Wol',
                               D9 = 'Donkere Kleding',
                               DA = 'Super Ecowas',
                               DB = 'Super Speed',
                               DC = '15 min Kort',
                               BA = 'Centrifugeren',
                               none = 'Niksen',
                               weightsensing = 'Wegen',
                               wash = 'Wassen',
                               rinse = 'Spoelen',
                               spin = 'Centrifugeren',
                               finish = 'Klaar',
                            }
                        return translationcode[code:gsub('Table_00_Course_','')] or translation[code]
                    end     
                local endprogram = 'Programma gereed'
                
                --Update textdevices only when status is changed to prevent too many irrelevant log rows
                local function updateTextOnlyWhenChanged( textSensorName, newText)
                    local textDevice = dz.devices(textSensorName)
                    if textDevice.text == newText then 
                        return 
                    else
                        textDevice.updateText(newText)
                    end
                end
                
                --Update percentagedevices only when status is changed to prevent too many irrelevant log rows
                local function updatePercentageOnlyWhenChanged( percentageSensorName, newPercentage)
                    local percentageDevice = dz.devices(percentageSensorName)
                    if percentageDevice.percentage == newPercentage then 
                        return 
                    else
                        percentage.updatePercentage(newPercentage)
                    end
                end
                
                local function convertTime(dateString, offset )                             --convert the time to Hour,Minutem,second.
                        local function makeTimeStamp(dateString)
                            local pattern = '(%d+)%-(%d+)%-(%d+)%T(%d+):(%d+):(%d+)(%.*)' -- %d+ = 1 or more digits , %.* = 0 or more any character
                            local xyear, xmonth, xday, xhour, xminute, xseconds = dateString:match(pattern) -- split the string using the pattern
                            local convertedTimestamp = os.time({year = xyear, month = xmonth, day = xday, hour = xhour, min = xminute, sec = xseconds})
                            return convertedTimestamp
                        end
                        return os.date('%H:%M:%S', makeTimeStamp(dateString) + offset )
                    end
                    
                    
                    local values = dz.utils.fromJSON(item.json.main.data.value)
                    local remainingTime = values.payload.remainingTime or  values.payload["x.com.samsung.da.remainingTime"] or 'not found'
                    local progressPercentage = values.payload.progressPercentage or  values.payload["x.com.samsung.da.progressPercentage"] or 'not found'
                    
                    
                    local completionTime = convertTime(rt.completionTime.value, 3600 )   --Making 1 hour ofset to get local time
                    local switch = rt.switch.value
                    local washerWaterTemperature = rt.washerWaterTemperature.value
                    local washerJobState = rt.washerJobState.value
                    local washerMode = rt.washerMode.value
                    local washerSpinLevel = rt.washerSpinLevel.value
                    
                    if switch == ('on') then                                            -- Turn on Domoitcz switches updates only when Washer is Active.
                            dz.log('Debuggg if swithc on:' ..  switch, dz.LOG_DEBUG)
                            wm_status.switchOn().checkFirst()     --turn on dz WM status switch
                            updateTextOnlyWhenChanged('WM Temperatuur', washerWaterTemperature )
                            updateTextOnlyWhenChanged('WM Aan het', codeToDutch(washerJobState))
                            updateTextOnlyWhenChanged('WM Toerental', washerSpinLevel)
                            updateTextOnlyWhenChanged('WM Resterend', remainingTime)
                            updateTextOnlyWhenChanged('WM Klaar om', completionTime)
                            updateTextOnlyWhenChanged('WM Programma', codeToDutch(washerMode)) 
                            updatePercentageOnlyWhenChanged('WM Percentage', progressPercentage)
                    else                                                                --Upate text deices with endprogram wen swithc is off
                                dz.log('Debuggg if switch off:' ..  switch, dz.LOG_DEBUG)
                                
                                wm_status.switchOff().checkFirst()
                                dz.log('washerMode if switch off:' ..  endprogram, dz.LOG_DEBUG)
                                updateTextOnlyWhenChanged('WM Temperatuur', endprogram)
                                updateTextOnlyWhenChanged('WM Aan het', endprogram)
                                updateTextOnlyWhenChanged('WM Toerental', endprogram)
                                updateTextOnlyWhenChanged('WM Resterend', endprogram)
                                updateTextOnlyWhenChanged('WM Klaar om', endprogram)
                                updateTextOnlyWhenChanged('WM Programma', endprogram)
                                updatePercentageOnlyWhenChanged('WM Percentage', 100)
                                
                     end        
                            if LOGGING then                                             
                                dz.log('\n-\nWhats happening: \n-\n ', dz.LOG_INFO)
                                dz.log('Klaar om:' .. completionTime, dz.LOG_INFO)
                                dz.log('Status:' .. switch, dz.LOG_INFO)
                                dz.log('Temperatuur:' .. washerWaterTemperature, dz.LOG_INFO)
                                dz.log('Aan het:' .. washerJobState, dz.LOG_INFO)
                                dz.log('Programma:' .. washerMode, dz.LOG_INFO)
                                dz.log('Toerental:' .. washerSpinLevel, dz.LOG_INFO)
                                dz.log('remaining time = ' .. remainingTime, dz.LOG_INFO) 
                                dz.log('progressPercentage  = ' .. progressPercentage, dz.LOG_INFO)
                                dz.log('\n-\n============================== \n-\n ', dz.LOG_INFO)
                            end
                   
                
                
                
                return
            else
                dz.log('result was not recognized as a JSON', dz.LOG_ERROR)
            end
        else
            dz.log('result was not OK', dz.LOG_ERROR)
        end
        dz.log(item,dz.LOG_ERROR) -- dump all to log as one long string
    end
}
Debian buster, bullseye on RPI-4, Intel NUC.
dz Beta, Z-Wave, RFLink, RFXtrx433e, P1, Youless, Hue, Yeelight, Xiaomi, MQTT
==>> dzVents wiki
Tjeerd13
Posts: 34
Joined: Thursday 07 May 2015 16:57
Target OS: Raspberry Pi / ODroid
Domoticz version: Beta
Location: Assen
Contact:

Re: Samsung Washmachine read status from json "SOLVED"

Post by Tjeerd13 »

I tried something like that, but thats not working it looks like I do not get the correct or any value of the dz device: WM Percentage.

With your script i get:
2020-02-29 15:49:01.079 Error: dzVents: Error: (3.0.0) wasmachine_JSON: An error occurred when calling event handler Samsung_v4
2020-02-29 15:49:01.079 Error: dzVents: Error: (3.0.0) wasmachine_JSON: ...omoticz/scripts/dzVents/generated_scripts/Samsung_v4.lua:118: attempt to index a nil value (global 'percentage')

How can i get the Value off DZ Device 'WM Percentage' . ? for Somethin like "

if dz.devices('WM Percentage') >= 80 and <= 100 then "Do something" end

or

if dz.devices('WM Percentage") ~= progressPercentage then dz.devices('WM Percentage').updatePercentage(progressPercentage) end
Pi3, Pi4, Pi4 for Testing, Dashticz, RFXtrx433, Nest: "Thermostat V2, V3, Hello". Honywell Lyric T6R, RFXCom, KaKu, HUE, P1, Open Zwave USB,
User avatar
waaren
Posts: 6028
Joined: Tuesday 03 January 2017 14:18
Target OS: Linux
Domoticz version: Beta
Location: Netherlands
Contact:

Re: Samsung Washmachine read status from json "SOLVED"

Post by waaren »

Tjeerd13 wrote: Saturday 29 February 2020 16:19 I tried something like that, but thats not working it looks like I do not get the correct or any value of the dz device: WM Percentage.
Try changing line 118 to
percentageDevice.updatePercentage(newPercentage)
Debian buster, bullseye on RPI-4, Intel NUC.
dz Beta, Z-Wave, RFLink, RFXtrx433e, P1, Youless, Hue, Yeelight, Xiaomi, MQTT
==>> dzVents wiki
Tjeerd13
Posts: 34
Joined: Thursday 07 May 2015 16:57
Target OS: Raspberry Pi / ODroid
Domoticz version: Beta
Location: Assen
Contact:

Re: Samsung Washmachine read status from json "SOLVED"

Post by Tjeerd13 »

That Worked!

How can i the item below get to work? Tried with en without percentage. Somtimes i get a Tabel Value error or a Nill Value

local WM_PERCENT = 'WM Percentage'
local wm_percent = dz.devices(WM_PERCENT)
dz.log('Percentage WM Percentage = ' .. dz.progressPercentage.wm_percent, dz.LOG_INFO)
Pi3, Pi4, Pi4 for Testing, Dashticz, RFXtrx433, Nest: "Thermostat V2, V3, Hello". Honywell Lyric T6R, RFXCom, KaKu, HUE, P1, Open Zwave USB,
User avatar
waaren
Posts: 6028
Joined: Tuesday 03 January 2017 14:18
Target OS: Linux
Domoticz version: Beta
Location: Netherlands
Contact:

Re: Samsung Washmachine read status from json "SOLVED"

Post by waaren »

Tjeerd13 wrote: Saturday 29 February 2020 17:20 dz.log('Percentage WM Percentage = ' .. dz.progressPercentage.wm_percent, dz.LOG_INFO)
If you want the current percentage from the domoticz device you should use
dz.log('Percentage WM Percentage = ' .. wm_percent.percentage .. '%' , dz.LOG_INFO)
Debian buster, bullseye on RPI-4, Intel NUC.
dz Beta, Z-Wave, RFLink, RFXtrx433e, P1, Youless, Hue, Yeelight, Xiaomi, MQTT
==>> dzVents wiki
Podarcis
Posts: 7
Joined: Sunday 26 April 2015 18:05
Target OS: Raspberry Pi / ODroid
Domoticz version:
Contact:

Re: Samsung Washmachine read status from json "SOLVED"

Post by Podarcis »

Code: Select all

--[[
	 Dummy textdevices WM Programma,  WM Klaar om, WM aan het, WM Toerental, WM Resterend, WM Temperatuus.
 	Dummy on/of switch WM Status
 	Dummy Percentaeg WM Percentage
 	API key from  https://developer.samsung.com/smartthings
 	Device ID from  https://smartthings.developer.samsung.com/docs/api-ref/st-api.html#operation/getDevices  i used postman to get the device. 
  	Making a get request with https://api.smartthings.com/v1/devices/ 
]]--
I think I managed to get a API-key, but how do I get the Device ID? I tried it with the smarthings-developer (https://smartthings.developer.samsung.c ... getDevices) site, but to no avail. 'Postman' doesn't ring a bell to me...

Isn't there a python, bash (or whatever) script to get the device ID?
Tjeerd13
Posts: 34
Joined: Thursday 07 May 2015 16:57
Target OS: Raspberry Pi / ODroid
Domoticz version: Beta
Location: Assen
Contact:

Re: Samsung Washmachine read status from json "SOLVED"

Post by Tjeerd13 »

Postman https://www.postman.com/product/api-client is a program you can download to visulize and request API request. Not needed but it gives me a lot of info from the API requests.

With this curl reqeust you can get all the device info from the command line (somewhere in the response look for "deviceId" ) (There is an space betwean Bearer and < YOUR API KEY> ! )

Code: Select all

curl --location --request GET 'https://api.smartthings.com/v1/devices/' \
--header 'Authorization: Bearer <Your API KEY>'
The below DzVents scripts dumps the Json data of the Samsung Devices from your API key in the log of Domoticz. This is only needed one time to get the Device ID.

Code: Select all

-- assumpitions for Samsung Getting Devices Wasmachine Script
--[[
	 
 	API key from  https://developer.samsung.com/smartthings
 	WHen activated you should find your  	'deviceTypeName' and	'deviceTypeId'  in the Domoticz log.
 	
 	I have only one samsung smart device. I expect that if you have more Samsung devices they al appear with diverent descriptions
]]--

local API = 'Your API KEY'
local scriptVar = 'Samsung_ID_JSON'

local LOGGING = true

return 
{
    on = 
    {
        timer = 
        {
            'every minute', -- just an example to trigger the request
        },
        
        devices =
        {
            50,              -- Just on Switch to activated the script manualy for testing.
        },
        httpResponses = 
        {
            scriptVar, -- must match with the callback passed to the openURL command
        },
    },
    
    logging = 
    { 
        level = domoticz.LOG_DEBUG,
        marker = scriptVar,
    }, 

    execute = function(dz, item)
    	local wm_status = dz.devices(WM_STATUS)
    	local wm_percent = dz.devices(WM_PERCENT)
        if item.isTimer or item.isDevice then
            dz.openURL({
                url = 'https://api.smartthings.com/v1/devices/',
                headers = { ['Authorization'] = 'Bearer '.. API },
                method = 'GET',
                callback = scriptVar, -- httpResponses above.
            })
            return
        elseif item.ok then
            
            if (item.isJSON) then -- when recognized as json then dzVents will convert it to a table for you
                rt = item.json.items
                
                    -- dump the string represenation of the complete table to log 
                     dz.log('\n-\nAnd now The Device INFO of your API \n-\n ', dz.LOG_DEBUG)
                    dz.utils.dumpTable(item.json) 
            return
        
            else
                dz.log('result was not recognized as a JSON', dz.LOG_ERROR)
            end
        else
            dz.log('result was not OK', dz.LOG_ERROR)
        end
        dz.log(item,dz.LOG_ERROR) -- dump all to log as one long string
    end
}
Pi3, Pi4, Pi4 for Testing, Dashticz, RFXtrx433, Nest: "Thermostat V2, V3, Hello". Honywell Lyric T6R, RFXCom, KaKu, HUE, P1, Open Zwave USB,
Podarcis
Posts: 7
Joined: Sunday 26 April 2015 18:05
Target OS: Raspberry Pi / ODroid
Domoticz version:
Contact:

Re: Samsung Washmachine read status from json "SOLVED"

Post by Podarcis »

That curl-command helped! Thanks. Working now like a breeze!
Post Reply

Who is online

Users browsing this forum: No registered users and 1 guest